Detached vs. Joinable POSIX threads

user191776 picture user191776 · Sep 21, 2010 · Viewed 34.7k times · Source

I've been using the pthread library for creating & joining threads in C.

  1. When should I create a thread as detached, right from the outset? Does it offer any performance advantage vs. a joinable thread?

  2. Is it legal to not do a pthread_join() on a joinable (by default) thread? Or should such a thread always use the detach() function before pthread_exit()ing?

Answer

Jonathan Leffler picture Jonathan Leffler · Sep 21, 2010
  1. Create a detached thread when you know you won't want to wait for it with pthread_join(). The only performance benefit is that when a detached thread terminates, its resources can be released immediately instead of having to wait for the thread to be joined before the resources can be released.

  2. It is 'legal' not to join a joinable thread; but it is not usually advisable because (as previously noted) the resources won't be released until the thread is joined, so they'll remain tied up indefinitely (until the program exits) if you don't join it.