1

I've been tasked with creating a user-level thread library that replicates the functionality of pthread (full disclosure: this is for an OS course). However, I'm unclear as to how pthread_join() and pthread_exit() interact when a thread has already exited.

In particular, the man page states:

The pthread_join() function waits for the thread specified by thread to terminate. If that thread has already terminated, then pthread_join() returns immediately.

Is this a guarantee that even if I create millions of threads their results will be kept available for one join? Otherwise, how long can I expect the result to be kept around?

I'm not looking for advice on how to implement it (that's most of the fun!), I'm just trying to nail down the behavior before I dive in.

piebie
  • 2,652
  • 21
  • 30
  • They'll hang around indefinitely, but obviously you can see that that might not be desirable.... There's also the concept of a "detached" thread, for which the threading library won't keep an exit value around waiting for a `join`. For posix threads, see http://linux.die.net/man/3/pthread_detach and http://linux.die.net/man/3/pthread_attr_setdetachstate – Tony Delroy Jan 17 '14 at 07:31
  • In fact for threads that aren't detached, you can think of `pthread_join` as being the function that you call to clean up the resources associated with storing the result of the thread. Much like `delete` is the call you make to clean up resources from `new`. – Steve Jessop Jan 17 '14 at 08:25
  • Interesting! We haven't been asked to replicate `pthread_detach` so I guess I'll just have to assume whatever tests the do on it won't leave too much hanging. – piebie Jan 17 '14 at 15:45

1 Answers1

3

There's no time limit, the implementation has to keep around the "return value" as long as the process itself is alive to make it available to a join.

The POSIX definition for pthread_exit simply says:

The pthread_exit() function shall terminate the calling thread and make the value value_ptr available to any successful join with the terminating thread.

Doesn't matter whether the join was initiated before the exit, or years later, or whether there was only one additional thread or hundreds.

Mat
  • 202,337
  • 40
  • 393
  • 406