Search code examples
multithreadingpthreadspthread-join

how to check if a pthread is joinable?


I know I can create a pthread with joinable attribute set, but once created,

  1. am I right that I can also change that pthread to a detached pthread?
  2. If that's the case, how can I check if a pthread is joinable? And how can I change a pthread from joinable to detached?

Solution

    1. Yes, you can. Just call pthread_detach() on the thread.
    2. You have several options.

    a. If you have launched your thread with specified pthread_attr, and this pthread_attr is still around, you can reliably check the joinable state by calling pthread_attr_getdetachstate. If pthread_attr is not available, and you are on Linux, you can requery for the attribute by calling pthread_getattr_np - note, that _np means non-Posix, so this will likely be Linux-only.

    b. You can simply try joining it. A pthread which is not joinable usually will return EINVAL. This is not standard with POSIX, but something you can rely upon with, for example, Linux - as well as Solaris and likely other major systems.

    c. The easiest option is to simply keep track of your threads yourself, so that you will always know if the particular thread is joinable simply by checking your program state.