pthread_tryjoin.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* Copyright (C) 2002, 2003, 2005 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
  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. <http://www.gnu.org/licenses/>. */
  15. #include <errno.h>
  16. #include <stdlib.h>
  17. #include <atomic.h>
  18. #include "pthreadP.h"
  19. int
  20. pthread_tryjoin_np (
  21. pthread_t threadid,
  22. void **thread_return)
  23. {
  24. struct pthread *self;
  25. struct pthread *pd = (struct pthread *) threadid;
  26. /* Make sure the descriptor is valid. */
  27. if (DEBUGGING_P && __find_in_stack_list (pd) == NULL)
  28. /* Not a valid thread handle. */
  29. return ESRCH;
  30. /* Is the thread joinable?. */
  31. if (IS_DETACHED (pd))
  32. /* We cannot wait for the thread. */
  33. return EINVAL;
  34. self = THREAD_SELF;
  35. if (pd == self || self->joinid == pd)
  36. /* This is a deadlock situation. The threads are waiting for each
  37. other to finish. Note that this is a "may" error. To be 100%
  38. sure we catch this error we would have to lock the data
  39. structures but it is not necessary. In the unlikely case that
  40. two threads are really caught in this situation they will
  41. deadlock. It is the programmer's problem to figure this
  42. out. */
  43. return EDEADLK;
  44. /* Return right away if the thread hasn't terminated yet. */
  45. if (pd->tid != 0)
  46. return EBUSY;
  47. /* Wait for the thread to finish. If it is already locked something
  48. is wrong. There can only be one waiter. */
  49. if (atomic_compare_and_exchange_bool_acq (&pd->joinid, self, NULL))
  50. /* There is already somebody waiting for the thread. */
  51. return EINVAL;
  52. /* Store the return value if the caller is interested. */
  53. if (thread_return != NULL)
  54. *thread_return = pd->result;
  55. /* Free the TCB. */
  56. __free_tcb (pd);
  57. return 0;
  58. }