[openbeos] Re: POSIX thread safety, was: Re: Waiting and waiting

  • From: argent@xxxxxxxxxxxxxxxxxx
  • To: openbeos@xxxxxxxxxxxxx
  • Date: Tue, 10 Dec 2002 20:22:26 -0500

on Tue, Dec 10, 2002 at 08:01:34PM -0500, Michael Phipps was heard to have 
remarked:
> >Although the POSIX standard may declare that these functions need not
> >be thread-safe, an implementation where they are thread-safe would
> >certainly satisfy POSIX.  In BeOS, where threads are pervasive, I'd
> >argue that all of the standard library should be thread-safe.
> 
> Thread safe may be a good thing or a bad thing.
> Example:
>       thread 1                                                                
> thread 2
> read (fd,buffer,2048);                                                
> acquire_sem(thread2Pause);
> char *foo=strtok(buffer,":");                                 char 
> *bar=strtok(NULL);
> release_sem(thread2Pause);                            // Process
> // Continue on doing other things...
> 
>
> Yeah, I know that this is a small, contrived example, but one
> *could* want and even expect that strtok works across threads.

Definitely.  And POSIX says we have to.  Remember, strtok, etc., while
not reentrant, can still be implemented in a thread-safe way.  All
that means is that two or more threads can call the function, and it
returns uncorrupted, correct data.  NOT that it returns thread-local
data, or that it returns what you expect.

For example:

thread1:                                thread2:
buffer = "too much fun";                char *bar = strtok(NULL, " ");
char *foo = strtok(buffer, " ");
// foo now contains "too"?
foo = strtok(NULL, " ");

Now, at the end of this, foo could contain "much" or "fun", and bar
could contain data from a previous strtok, or, if thread2 was stalled
on the first instruction of strtok until after thread1 called strtok,
it could have something from there.  (Even "too", I'd think.)  If
strtok is not thread-safe, the contents of foo and bar and
*undefined*.  Or the program could just segfault.

So, we should have a thread-safe, and re-entrant where possible, but
POSIX-compliant in all cases.  [It makes life easier that way.]

-- 
Evan Knop <argent@xxxxxxxxxxx>      http://lore.dartmouth.edu/~argent/

Doubt is not a pleasant condition, but certainty is absurd.
- Voltaire

Other related posts: