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 <__chrono/time_point.h>
50#include <__config>
51#include <__thread/timed_backoff_policy.h>
52#include <__threading_support>
53#include <atomic>
54#include <version>
55
56#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
57#  pragma GCC system_header
58#endif
59
60#ifdef _LIBCPP_HAS_NO_THREADS
61# error <semaphore> is not supported on this single threaded system
62#endif
63
64_LIBCPP_PUSH_MACROS
65#include <__undef_macros>
66
67#if _LIBCPP_STD_VER >= 14
68
69_LIBCPP_BEGIN_NAMESPACE_STD
70
71/*
72
73__atomic_semaphore_base is the general-case implementation.
74It is a typical Dijkstra semaphore algorithm over atomics, wait and notify
75functions. It avoids contention against users' own use of those facilities.
76
77*/
78
79class __atomic_semaphore_base
80{
81    __atomic_base<ptrdiff_t> __a;
82
83public:
84    _LIBCPP_INLINE_VISIBILITY
85    constexpr explicit __atomic_semaphore_base(ptrdiff_t __count) : __a(__count)
86    {
87    }
88    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
89    void release(ptrdiff_t __update = 1)
90    {
91        if(0 < __a.fetch_add(__update, memory_order_release))
92            ;
93        else if(__update > 1)
94            __a.notify_all();
95        else
96            __a.notify_one();
97    }
98    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
99    void acquire()
100    {
101        auto const __test_fn = [this]() -> bool {
102            auto __old = __a.load(memory_order_relaxed);
103            return (__old != 0) && __a.compare_exchange_strong(__old, __old - 1, memory_order_acquire, memory_order_relaxed);
104        };
105        __cxx_atomic_wait(&__a.__a_, __test_fn);
106    }
107    template <class Rep, class Period>
108    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
109    bool try_acquire_for(chrono::duration<Rep, Period> const& __rel_time)
110    {
111        if (__rel_time == chrono::duration<Rep, Period>::zero())
112            return try_acquire();
113        auto const __test_fn = [this]() { return try_acquire(); };
114        return __libcpp_thread_poll_with_backoff(__test_fn, __libcpp_timed_backoff_policy(), __rel_time);
115    }
116    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
117    bool try_acquire()
118    {
119        auto __old = __a.load(memory_order_acquire);
120        while (true) {
121            if (__old == 0)
122                return false;
123            if (__a.compare_exchange_strong(__old, __old - 1, memory_order_acquire, memory_order_relaxed))
124                return true;
125        }
126    }
127};
128
129#define _LIBCPP_SEMAPHORE_MAX (numeric_limits<ptrdiff_t>::max())
130
131template<ptrdiff_t __least_max_value = _LIBCPP_SEMAPHORE_MAX>
132class counting_semaphore
133{
134    __atomic_semaphore_base __semaphore;
135
136public:
137    static constexpr ptrdiff_t max() noexcept {
138        return __least_max_value;
139    }
140
141    _LIBCPP_INLINE_VISIBILITY
142    constexpr explicit counting_semaphore(ptrdiff_t __count) : __semaphore(__count) { }
143    ~counting_semaphore() = default;
144
145    counting_semaphore(const counting_semaphore&) = delete;
146    counting_semaphore& operator=(const counting_semaphore&) = delete;
147
148    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
149    void release(ptrdiff_t __update = 1)
150    {
151        __semaphore.release(__update);
152    }
153    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
154    void acquire()
155    {
156        __semaphore.acquire();
157    }
158    template<class Rep, class Period>
159    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
160    bool try_acquire_for(chrono::duration<Rep, Period> const& __rel_time)
161    {
162        return __semaphore.try_acquire_for(chrono::duration_cast<chrono::nanoseconds>(__rel_time));
163    }
164    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
165    bool try_acquire()
166    {
167        return __semaphore.try_acquire();
168    }
169    template <class Clock, class Duration>
170    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
171    bool try_acquire_until(chrono::time_point<Clock, Duration> const& __abs_time)
172    {
173        auto const current = Clock::now();
174        if (current >= __abs_time)
175            return try_acquire();
176        else
177            return try_acquire_for(__abs_time - current);
178    }
179};
180
181using binary_semaphore = counting_semaphore<1>;
182
183_LIBCPP_END_NAMESPACE_STD
184
185#endif // _LIBCPP_STD_VER >= 14
186
187_LIBCPP_POP_MACROS
188
189#endif //_LIBCPP_SEMAPHORE
190