1 | /* Detach a thread. |
---|---|
2 | Copyright (C) 2000-2022 Free Software Foundation, Inc. |
3 | This file is part of the GNU C Library. |
4 | |
5 | The GNU C Library is free software; you can redistribute it and/or |
6 | modify it under the terms of the GNU Lesser General Public |
7 | License as published by the Free Software Foundation; either |
8 | version 2.1 of the License, or (at your option) any later version. |
9 | |
10 | The GNU C Library is distributed in the hope that it will be useful, |
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
13 | Lesser General Public License for more details. |
14 | |
15 | You should have received a copy of the GNU Lesser General Public |
16 | License along with the GNU C Library; if not, see |
17 | <https://www.gnu.org/licenses/>. */ |
18 | |
19 | #include <errno.h> |
20 | #include <pthread.h> |
21 | #include <stddef.h> |
22 | |
23 | #include <pt-internal.h> |
24 | |
25 | /* Indicate that the storage for THREAD can be reclaimed when it |
26 | terminates. */ |
27 | int |
28 | __pthread_detach (pthread_t thread) |
29 | { |
30 | struct __pthread *pthread; |
31 | int err = 0; |
32 | |
33 | /* Lookup the thread structure for THREAD. */ |
34 | pthread = __pthread_getid (thread); |
35 | if (pthread == NULL) |
36 | return ESRCH; |
37 | |
38 | __pthread_mutex_lock (&pthread->state_lock); |
39 | |
40 | switch (pthread->state) |
41 | { |
42 | case PTHREAD_JOINABLE: |
43 | /* THREAD still running. Mark it as detached such that its |
44 | resources can be reclaimed as soon as the thread exits. */ |
45 | pthread->state = PTHREAD_DETACHED; |
46 | |
47 | /* Broadcast the condition. This will make threads that are |
48 | waiting to join THREAD continue with hopefully disastrous |
49 | consequences instead of blocking indefinitely. */ |
50 | __pthread_cond_broadcast (&pthread->state_cond); |
51 | __pthread_mutex_unlock (&pthread->state_lock); |
52 | |
53 | __pthread_dealloc (thread: pthread); |
54 | break; |
55 | |
56 | case PTHREAD_EXITED: |
57 | __pthread_mutex_unlock (&pthread->state_lock); |
58 | |
59 | /* THREAD has already exited. PTHREAD remained after the thread |
60 | exited in order to provide the exit status, but it turns out |
61 | it won't be needed. */ |
62 | __pthread_dealloc (thread: pthread); |
63 | break; |
64 | |
65 | default: |
66 | /* Thou shalt not detach non-joinable threads! */ |
67 | __pthread_mutex_unlock (&pthread->state_lock); |
68 | err = EINVAL; |
69 | break; |
70 | } |
71 | |
72 | return err; |
73 | } |
74 | weak_alias (__pthread_detach, pthread_detach) |
75 | hidden_def (__pthread_detach) |
76 |