1// -*- C++ -*-
2//===----------------------------------------------------------------------===//
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 <__availability>
49#include <__config>
50#include <__threading_support>
51#include <atomic>
52#include <version>
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_LIBCPP_PUSH_MACROS
63#include <__undef_macros>
64
65#if _LIBCPP_STD_VER >= 14
66
67_LIBCPP_BEGIN_NAMESPACE_STD
68
69/*
70
71__atomic_semaphore_base is the general-case implementation.
72It is a typical Dijkstra 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    constexpr explicit __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 = [this]() -> 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        if (__rel_time == chrono::duration<Rep, Period>::zero())
110            return try_acquire();
111        auto const __test_fn = [this]() { return try_acquire(); };
112        return __libcpp_thread_poll_with_backoff(__test_fn, __libcpp_timed_backoff_policy(), __rel_time);
113    }
114    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
115    bool try_acquire()
116    {
117        auto __old = __a.load(memory_order_acquire);
118        while (true) {
119            if (__old == 0)
120                return false;
121            if (__a.compare_exchange_strong(__old, __old - 1, memory_order_acquire, memory_order_relaxed))
122                return true;
123        }
124    }
125};
126
127#define _LIBCPP_SEMAPHORE_MAX (numeric_limits<ptrdiff_t>::max())
128
129template<ptrdiff_t __least_max_value = _LIBCPP_SEMAPHORE_MAX>
130class counting_semaphore
131{
132    __atomic_semaphore_base __semaphore;
133
134public:
135    static constexpr ptrdiff_t max() noexcept {
136        return __least_max_value;
137    }
138
139    _LIBCPP_INLINE_VISIBILITY
140    constexpr explicit counting_semaphore(ptrdiff_t __count) : __semaphore(__count) { }
141    ~counting_semaphore() = default;
142
143    counting_semaphore(const counting_semaphore&) = delete;
144    counting_semaphore& operator=(const counting_semaphore&) = delete;
145
146    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
147    void release(ptrdiff_t __update = 1)
148    {
149        __semaphore.release(__update);
150    }
151    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
152    void acquire()
153    {
154        __semaphore.acquire();
155    }
156    template<class Rep, class Period>
157    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
158    bool try_acquire_for(chrono::duration<Rep, Period> const& __rel_time)
159    {
160        return __semaphore.try_acquire_for(chrono::duration_cast<chrono::nanoseconds>(__rel_time));
161    }
162    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
163    bool try_acquire()
164    {
165        return __semaphore.try_acquire();
166    }
167    template <class Clock, class Duration>
168    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
169    bool try_acquire_until(chrono::time_point<Clock, Duration> const& __abs_time)
170    {
171        auto const current = Clock::now();
172        if (current >= __abs_time)
173            return try_acquire();
174        else
175            return try_acquire_for(__abs_time - current);
176    }
177};
178
179using binary_semaphore = counting_semaphore<1>;
180
181_LIBCPP_END_NAMESPACE_STD
182
183#endif // _LIBCPP_STD_VER >= 14
184
185_LIBCPP_POP_MACROS
186
187#endif //_LIBCPP_SEMAPHORE
188