]> git.ipfire.org Git - thirdparty/glibc.git/blame - sysdeps/htl/sem-timedwait.c
hurd: Bump remaining LGPL2+ htl licences to LGPL 2.1+
[thirdparty/glibc.git] / sysdeps / htl / sem-timedwait.c
CommitLineData
33574c17
ST
1/* Wait on a semaphore with a timeout. Generic version.
2 Copyright (C) 2005-2018 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
5 The GNU C Library is free software; you can redistribute it and/or
ad2b41bf
ST
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.
33574c17
ST
9
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
ad2b41bf 13 Lesser General Public License for more details.
33574c17 14
ad2b41bf
ST
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <http://www.gnu.org/licenses/>. */
33574c17
ST
18
19#include <semaphore.h>
20#include <errno.h>
21#include <assert.h>
22
23#include <pt-internal.h>
24
25int
26__sem_timedwait_internal (sem_t *restrict sem,
27 const struct timespec *restrict timeout)
28{
29 error_t err;
30 int drain;
31 struct __pthread *self;
32
33 __pthread_spin_lock (&sem->__lock);
34 if (sem->__value > 0)
35 /* Successful down. */
36 {
37 sem->__value--;
38 __pthread_spin_unlock (&sem->__lock);
39 return 0;
40 }
41
42 if (timeout != NULL && (timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000))
43 {
44 errno = EINVAL;
45 return -1;
46 }
47
48 /* Add ourselves to the queue. */
49 self = _pthread_self ();
50
51 __pthread_enqueue (&sem->__queue, self);
52 __pthread_spin_unlock (&sem->__lock);
53
54 /* Block the thread. */
55 if (timeout != NULL)
56 err = __pthread_timedblock (self, timeout, CLOCK_REALTIME);
57 else
58 {
59 err = 0;
60 __pthread_block (self);
61 }
62
63 __pthread_spin_lock (&sem->__lock);
64 if (self->prevp == NULL)
65 /* Another thread removed us from the queue, which means a wakeup message
66 has been sent. It was either consumed while we were blocking, or
67 queued after we timed out and before we acquired the semaphore lock, in
68 which case the message queue must be drained. */
69 drain = err ? 1 : 0;
70 else
71 {
72 /* We're still in the queue. Noone attempted to wake us up, i.e. we
73 timed out. */
74 __pthread_dequeue (self);
75 drain = 0;
76 }
77 __pthread_spin_unlock (&sem->__lock);
78
79 if (drain)
80 __pthread_block (self);
81
82 if (err)
83 {
84 assert (err == ETIMEDOUT);
85 errno = err;
86 return -1;
87 }
88
89 return 0;
90}
91
92int
93__sem_timedwait (sem_t *restrict sem, const struct timespec *restrict timeout)
94{
95 return __sem_timedwait_internal (sem, timeout);
96}
97
98weak_alias (__sem_timedwait, sem_timedwait);