1 /* Deallocate a thread structure.
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 <assert.h>
20 #include <pthread.h>
21 #include <stdlib.h>
22 
23 #include <pt-internal.h>
24 
25 #include <atomic.h>
26 
27 /* List of thread structures corresponding to free thread IDs.  */
28 extern struct __pthread *__pthread_free_threads;
29 extern pthread_mutex_t __pthread_free_threads_lock;
30 
31 
32 /* Deallocate the content of the thread structure for PTHREAD.  */
33 void
__pthread_dealloc(struct __pthread * pthread)34 __pthread_dealloc (struct __pthread *pthread)
35 {
36   if (!atomic_decrement_and_test (&pthread->nr_refs))
37     return;
38 
39   /* Withdraw this thread from the thread ID lookup table.  */
40   __pthread_setid (pthread->thread, NULL);
41 
42   /* Mark the thread as terminated.  We broadcast the condition
43      here to prevent pthread_join from waiting for this thread to
44      exit where it was never really started.  Such a call to
45      pthread_join is completely bogus, but unfortunately allowed
46      by the standards.  */
47   __pthread_mutex_lock (&pthread->state_lock);
48   if (pthread->state != PTHREAD_EXITED)
49     __pthread_cond_broadcast (&pthread->state_cond);
50   __pthread_mutex_unlock (&pthread->state_lock);
51 
52   /* We do not actually deallocate the thread structure, but add it to
53      a list of re-usable thread structures.  */
54   __pthread_mutex_lock (&__pthread_free_threads_lock);
55   __pthread_enqueue (&__pthread_free_threads, pthread);
56   __pthread_mutex_unlock (&__pthread_free_threads_lock);
57 }
58 
59 /* Confirm deallocation of the thread structure for PTHREAD.  */
60 void
__pthread_dealloc_finish(struct __pthread * pthread)61 __pthread_dealloc_finish (struct __pthread *pthread)
62 {
63   /* Setting PTHREAD->TERMINATED makes this TCB
64      available for reuse.  After that point, we can no longer assume
65      that PTHREAD is valid.
66 
67      Note that it is safe to not lock this update to PTHREAD->STATE:
68      the only way that it can now be accessed is in __pthread_alloc,
69      which reads this variable.  */
70   pthread->terminated = TRUE;
71 }
72