tst-getdate: Improve testcase flexibility and add test.
[glibc.git] / htl / pt-detach.c
blob63471d129f0649db1aa174e66bcb9856f88a03c6
1 /* Detach a thread.
2 Copyright (C) 2000-2023 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
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.
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.
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/>. */
19 #include <errno.h>
20 #include <pthread.h>
21 #include <stddef.h>
23 #include <pt-internal.h>
25 /* Indicate that the storage for THREAD can be reclaimed when it
26 terminates. */
27 int
28 __pthread_detach (pthread_t thread)
30 struct __pthread *pthread;
31 int err = 0;
33 /* Lookup the thread structure for THREAD. */
34 pthread = __pthread_getid (thread);
35 if (pthread == NULL)
36 return ESRCH;
38 __pthread_mutex_lock (&pthread->state_lock);
40 switch (pthread->state)
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;
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);
53 __pthread_dealloc (pthread);
54 break;
56 case PTHREAD_EXITED:
57 __pthread_mutex_unlock (&pthread->state_lock);
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 (pthread);
63 break;
65 default:
66 /* Thou shalt not detach non-joinable threads! */
67 __pthread_mutex_unlock (&pthread->state_lock);
68 err = EINVAL;
69 break;
72 return err;
74 weak_alias (__pthread_detach, pthread_detach)
75 hidden_def (__pthread_detach)