sem_wait.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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, write to the Free
  15. Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  16. 02111-1307 USA. */
  17. #include <errno.h>
  18. #include <sysdep.h>
  19. #include <lowlevellock.h>
  20. #include <internaltypes.h>
  21. #include <semaphore.h>
  22. #include <pthreadP.h>
  23. void
  24. attribute_hidden
  25. __sem_wait_cleanup (void *arg)
  26. {
  27. struct new_sem *isem = (struct new_sem *) arg;
  28. atomic_decrement (&isem->nwaiters);
  29. }
  30. int
  31. sem_wait (sem_t *sem)
  32. {
  33. struct new_sem *isem = (struct new_sem *) sem;
  34. int err;
  35. if (atomic_decrement_if_positive (&isem->value) > 0)
  36. return 0;
  37. atomic_increment (&isem->nwaiters);
  38. pthread_cleanup_push (__sem_wait_cleanup, isem);
  39. while (1)
  40. {
  41. /* Enable asynchronous cancellation. Required by the standard. */
  42. int oldtype = __pthread_enable_asynccancel ();
  43. err = lll_futex_wait (&isem->value, 0,
  44. isem->private ^ FUTEX_PRIVATE_FLAG);
  45. /* Disable asynchronous cancellation. */
  46. __pthread_disable_asynccancel (oldtype);
  47. if (err != 0 && err != -EWOULDBLOCK)
  48. {
  49. __set_errno (-err);
  50. err = -1;
  51. break;
  52. }
  53. if (atomic_decrement_if_positive (&isem->value) > 0)
  54. {
  55. err = 0;
  56. break;
  57. }
  58. }
  59. pthread_cleanup_pop (0);
  60. atomic_decrement (&isem->nwaiters);
  61. return err;
  62. }