pthread_tryjoin.c 2.4 KB

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