1// -*- C++ -*-
2//===--------------------------- semaphore --------------------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef _LIBCPP_SEMAPHORE
11#define _LIBCPP_SEMAPHORE
12
13/*
14    semaphore synopsis
15
16namespace std {
17
18template<ptrdiff_t least_max_value = implementation-defined>
19class counting_semaphore
20{
21public:
22static constexpr ptrdiff_t max() noexcept;
23
24constexpr explicit counting_semaphore(ptrdiff_t desired);
25~counting_semaphore();
26
27counting_semaphore(const counting_semaphore&) = delete;
28counting_semaphore& operator=(const counting_semaphore&) = delete;
29
30void release(ptrdiff_t update = 1);
31void acquire();
32bool try_acquire() noexcept;
33template<class Rep, class Period>
34    bool try_acquire_for(const chrono::duration<Rep, Period>& rel_time);
35template<class Clock, class Duration>
36    bool try_acquire_until(const chrono::time_point<Clock, Duration>& abs_time);
37
38private:
39ptrdiff_t counter; // exposition only
40};
41
42using binary_semaphore = counting_semaphore<1>;
43
44}
45
46*/
47
48#include <__config>
49#include <__availability>
50#include <__threading_support>
51#include <atomic>
52#include <cassert>
53
54#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
55#pragma GCC system_header
56#endif
57
58#ifdef _LIBCPP_HAS_NO_THREADS
59# error <semaphore> is not supported on this single threaded system
60#endif
61
62#if _LIBCPP_STD_VER >= 14
63
64_LIBCPP_BEGIN_NAMESPACE_STD
65
66/*
67
68__atomic_semaphore_base is the general-case implementation, to be used for
69user-requested least-max values that exceed the OS implementation support
70(incl. when the OS has no support of its own) and for binary semaphores.
71
72It is a typical Dijsktra semaphore algorithm over atomics, wait and notify
73functions. It avoids contention against users' own use of those facilities.
74
75*/
76
77class __atomic_semaphore_base
78{
79    __atomic_base<ptrdiff_t> __a;
80
81public:
82    _LIBCPP_INLINE_VISIBILITY
83    __atomic_semaphore_base(ptrdiff_t __count) : __a(__count)
84    {
85    }
86    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
87    void release(ptrdiff_t __update = 1)
88    {
89        if(0 < __a.fetch_add(__update, memory_order_release))
90            ;
91        else if(__update > 1)
92            __a.notify_all();
93        else
94            __a.notify_one();
95    }
96    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
97    void acquire()
98    {
99        auto const __test_fn = [=]() -> bool {
100            auto __old = __a.load(memory_order_relaxed);
101            return (__old != 0) && __a.compare_exchange_strong(__old, __old - 1, memory_order_acquire, memory_order_relaxed);
102        };
103        __cxx_atomic_wait(&__a.__a_, __test_fn);
104    }
105    template <class Rep, class Period>
106    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
107    bool try_acquire_for(chrono::duration<Rep, Period> const& __rel_time)
108    {
109        auto const __test_fn = [=]() -> bool {
110            auto __old = __a.load(memory_order_acquire);
111            while(1) {
112                if (__old == 0)
113                    return false;
114                if(__a.compare_exchange_strong(__old, __old - 1, memory_order_acquire, memory_order_relaxed))
115                    return true;
116            }
117        };
118        return __libcpp_thread_poll_with_backoff(__test_fn, __libcpp_timed_backoff_policy(), __rel_time);
119    }
120};
121
122#ifndef _LIBCPP_NO_NATIVE_SEMAPHORES
123
124/*
125
126__platform_semaphore_base a simple wrapper for the OS semaphore type. That
127is, every call is routed to the OS in the most direct manner possible.
128
129*/
130
131class __platform_semaphore_base
132{
133    __libcpp_semaphore_t __semaphore;
134
135public:
136    _LIBCPP_INLINE_VISIBILITY
137    __platform_semaphore_base(ptrdiff_t __count) :
138        __semaphore()
139    {
140        __libcpp_semaphore_init(&__semaphore, __count);
141    }
142    _LIBCPP_INLINE_VISIBILITY
143    ~__platform_semaphore_base() {
144        __libcpp_semaphore_destroy(&__semaphore);
145    }
146    _LIBCPP_INLINE_VISIBILITY
147    void release(ptrdiff_t __update)
148    {
149        for(; __update; --__update)
150            __libcpp_semaphore_post(&__semaphore);
151    }
152    _LIBCPP_INLINE_VISIBILITY
153    void acquire()
154    {
155        __libcpp_semaphore_wait(&__semaphore);
156    }
157    _LIBCPP_INLINE_VISIBILITY
158    bool try_acquire_for(chrono::nanoseconds __rel_time)
159    {
160        return __libcpp_semaphore_wait_timed(&__semaphore, __rel_time);
161    }
162};
163
164template<ptrdiff_t __least_max_value>
165using __semaphore_base =
166    typename conditional<(__least_max_value > 1 && __least_max_value <= _LIBCPP_SEMAPHORE_MAX),
167                         __platform_semaphore_base,
168                         __atomic_semaphore_base>::type;
169
170#else
171
172template<ptrdiff_t __least_max_value>
173using __semaphore_base =
174    __atomic_semaphore_base;
175
176#define _LIBCPP_SEMAPHORE_MAX (numeric_limits<ptrdiff_t>::max())
177
178#endif //_LIBCPP_NO_NATIVE_SEMAPHORES
179
180template<ptrdiff_t __least_max_value = _LIBCPP_SEMAPHORE_MAX>
181class counting_semaphore
182{
183    __semaphore_base<__least_max_value> __semaphore;
184
185public:
186    static constexpr ptrdiff_t max() noexcept {
187        return __least_max_value;
188    }
189
190    _LIBCPP_INLINE_VISIBILITY
191    counting_semaphore(ptrdiff_t __count = 0) : __semaphore(__count) { }
192    ~counting_semaphore() = default;
193
194    counting_semaphore(const counting_semaphore&) = delete;
195    counting_semaphore& operator=(const counting_semaphore&) = delete;
196
197    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
198    void release(ptrdiff_t __update = 1)
199    {
200        __semaphore.release(__update);
201    }
202    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
203    void acquire()
204    {
205        __semaphore.acquire();
206    }
207    template<class Rep, class Period>
208    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
209    bool try_acquire_for(chrono::duration<Rep, Period> const& __rel_time)
210    {
211        return __semaphore.try_acquire_for(chrono::duration_cast<chrono::nanoseconds>(__rel_time));
212    }
213    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
214    bool try_acquire()
215    {
216        return try_acquire_for(chrono::nanoseconds::zero());
217    }
218    template <class Clock, class Duration>
219    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
220    bool try_acquire_until(chrono::time_point<Clock, Duration> const& __abs_time)
221    {
222        auto const current = Clock::now();
223        if(current >= __abs_time)
224            return try_acquire();
225        else
226            return try_acquire_for(__abs_time - current);
227    }
228};
229
230using binary_semaphore = counting_semaphore<1>;
231
232_LIBCPP_END_NAMESPACE_STD
233
234#endif // _LIBCPP_STD_VER >= 14
235
236#endif //_LIBCPP_SEMAPHORE
237