1 /* Copyright (C) 2005-2021 Free Software Foundation, Inc.
2 Contributed by Richard Henderson <rth@redhat.com>.
4 This file is part of the GNU Offloading and Multi Processing Library
7 Libgomp is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
12 Libgomp is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 FOR A PARTICULAR PURPOSE. See the GNU General Public License for
17 Under Section 7 of GPL version 3, you are granted additional
18 permissions described in the GCC Runtime Library Exception, version
19 3.1, as published by the Free Software Foundation.
21 You should have received a copy of the GNU General Public License and
22 a copy of the GCC Runtime Library Exception along with this program;
23 see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
24 <http://www.gnu.org/licenses/>. */
26 /* This is a Linux specific implementation of a semaphore synchronization
27 mechanism for libgomp. This type is private to the library. This
28 implementation uses atomic instructions and the futex syscall. */
33 gomp_sem_wait_slow (gomp_sem_t
*sem
, int count
)
35 /* First loop spins a while. */
38 /* Spin timeout, nothing changed. Set waiting flag. */
39 && __atomic_compare_exchange_n (sem
, &count
, SEM_WAIT
, false,
40 MEMMODEL_ACQUIRE
, MEMMODEL_RELAXED
))
42 futex_wait (sem
, SEM_WAIT
);
46 /* Something changed. If it wasn't the wait flag, we're good to go. */
47 else if (__builtin_expect (((count
= *sem
) & SEM_WAIT
) == 0 && count
!= 0,
50 if (__atomic_compare_exchange_n (sem
, &count
, count
- SEM_INC
, false,
51 MEMMODEL_ACQUIRE
, MEMMODEL_RELAXED
))
55 /* Second loop waits until semaphore is posted. We always exit this
56 loop with wait flag set, so next post will awaken a thread. */
59 unsigned int wake
= count
& ~SEM_WAIT
;
60 int newval
= SEM_WAIT
;
63 newval
|= wake
- SEM_INC
;
64 if (__atomic_compare_exchange_n (sem
, &count
, newval
, false,
65 MEMMODEL_ACQUIRE
, MEMMODEL_RELAXED
))
69 /* If we can wake more threads, do so now. */
71 gomp_sem_post_slow (sem
);
74 do_wait (sem
, SEM_WAIT
);
81 gomp_sem_post_slow (gomp_sem_t
*sem
)