sem_wait.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* sem_wait -- wait on a semaphore. Generic futex-using version.
  2. Copyright (C) 2003, 2007 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. Contributed by Paul Mackerras <paulus@au.ibm.com>, 2003.
  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. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public
  14. License along with the GNU C Library; if not, see
  15. <http://www.gnu.org/licenses/>. */
  16. #include <errno.h>
  17. #include <sysdep.h>
  18. #include <lowlevellock.h>
  19. #include <internaltypes.h>
  20. #include <semaphore.h>
  21. #include <pthreadP.h>
  22. void
  23. attribute_hidden
  24. __sem_wait_cleanup (void *arg)
  25. {
  26. struct new_sem *isem = (struct new_sem *) arg;
  27. atomic_decrement (&isem->nwaiters);
  28. }
  29. int
  30. sem_wait (sem_t *sem)
  31. {
  32. struct new_sem *isem = (struct new_sem *) sem;
  33. int err;
  34. if (atomic_decrement_if_positive (&isem->value) > 0)
  35. return 0;
  36. atomic_increment (&isem->nwaiters);
  37. pthread_cleanup_push (__sem_wait_cleanup, isem);
  38. while (1)
  39. {
  40. /* Enable asynchronous cancellation. Required by the standard. */
  41. int oldtype = __pthread_enable_asynccancel ();
  42. err = lll_futex_wait (&isem->value, 0,
  43. isem->private ^ FUTEX_PRIVATE_FLAG);
  44. /* Disable asynchronous cancellation. */
  45. __pthread_disable_asynccancel (oldtype);
  46. if (err != 0 && err != -EWOULDBLOCK)
  47. {
  48. __set_errno (-err);
  49. err = -1;
  50. break;
  51. }
  52. if (atomic_decrement_if_positive (&isem->value) > 0)
  53. {
  54. err = 0;
  55. break;
  56. }
  57. }
  58. pthread_cleanup_pop (0);
  59. atomic_decrement (&isem->nwaiters);
  60. return err;
  61. }