sem_timedwait.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /* sem_timedwait -- wait on a semaphore. Generic futex-using version.
  2. Copyright (C) 2003 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. int
  24. sem_timedwait (sem_t *sem, const struct timespec *abstime)
  25. {
  26. /* First check for cancellation. */
  27. CANCELLATION_P (THREAD_SELF);
  28. int *futex = (int *) sem;
  29. int val;
  30. int err;
  31. if (*futex > 0)
  32. {
  33. val = atomic_decrement_if_positive (futex);
  34. if (val > 0)
  35. return 0;
  36. }
  37. err = -EINVAL;
  38. if (abstime->tv_nsec < 0 || abstime->tv_nsec >= 1000000000)
  39. goto error_return;
  40. do
  41. {
  42. struct timeval tv;
  43. struct timespec rt;
  44. int sec, nsec;
  45. /* Get the current time. */
  46. gettimeofday (&tv, NULL);
  47. /* Compute relative timeout. */
  48. sec = abstime->tv_sec - tv.tv_sec;
  49. nsec = abstime->tv_nsec - tv.tv_usec * 1000;
  50. if (nsec < 0)
  51. {
  52. nsec += 1000000000;
  53. --sec;
  54. }
  55. /* Already timed out? */
  56. err = -ETIMEDOUT;
  57. if (sec < 0)
  58. goto error_return;
  59. /* Do wait. */
  60. rt.tv_sec = sec;
  61. rt.tv_nsec = nsec;
  62. /* Enable asynchronous cancellation. Required by the standard. */
  63. int oldtype = __pthread_enable_asynccancel ();
  64. err = lll_futex_timed_wait (futex, 0, &rt);
  65. /* Disable asynchronous cancellation. */
  66. __pthread_disable_asynccancel (oldtype);
  67. if (err != 0 && err != -EWOULDBLOCK)
  68. goto error_return;
  69. val = atomic_decrement_if_positive (futex);
  70. }
  71. while (val <= 0);
  72. return 0;
  73. error_return:
  74. __set_errno (-err);
  75. return -1;
  76. }