pt-detach.c 2.5 KB

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