path: root/src/thread/pthread_detach.c
diff options
authorRich Felker <>2018-05-05 21:33:58 -0400
committerRich Felker <>2018-05-05 21:33:58 -0400
commitcdba6b2562bc5c2078e0e1e6f86c8835a42ae4ff (patch)
treef452bf4d2f4275ae2945ef860826f6640e8fc830 /src/thread/pthread_detach.c
parent526e64f54d729947b35fd39129bc86cbc0b5f098 (diff)
improve joinable/detached thread state handling
previously, some accesses to the detached state (from pthread_join and pthread_getattr_np) were unsynchronized; they were harmless in programs with well-defined behavior, but ugly. other accesses (in pthread_exit and pthread_detach) were synchronized by a poorly named "exitlock", with an ad-hoc trylock operation on it open-coded in pthread_detach, whose only purpose was establishing protocol for which thread is responsible for deallocation of detached-thread resources. instead, use an atomic detach_state and unify it with the futex used to wait for thread exit. this eliminates 2 members from the pthread structure, gets rid of the hackish lock usage, and makes rigorous the trap added in commit 80bf5952551c002cf12d96deb145629765272db0 for catching attempts to join detached threads. it should also make attempt to detach an already-detached thread reliably trap.
Diffstat (limited to 'src/thread/pthread_detach.c')
1 files changed, 3 insertions, 4 deletions
diff --git a/src/thread/pthread_detach.c b/src/thread/pthread_detach.c
index 692bbaf9..9cee7a89 100644
--- a/src/thread/pthread_detach.c
+++ b/src/thread/pthread_detach.c
@@ -5,11 +5,10 @@ int __pthread_join(pthread_t, void **);
static int __pthread_detach(pthread_t t)
- /* Cannot detach a thread that's already exiting */
- if (a_cas(t->exitlock, 0, INT_MIN + 1))
+ /* If the cas fails, detach state is either already-detached
+ * or exiting/exited, and pthread_join will trap or cleanup. */
+ if (a_cas(&t->detach_state, DT_JOINABLE, DT_DYNAMIC) != DT_JOINABLE)
return __pthread_join(t, 0);
- t->detached = 2;
- UNLOCK(t->exitlock);
return 0;