xref: /freebsd/contrib/llvm-project/libcxx/include/semaphore (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
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 <__assert> // all public C++ headers provide the assertion handler
49#include <__atomic/atomic_base.h>
50#include <__atomic/atomic_sync.h>
51#include <__atomic/memory_order.h>
52#include <__availability>
53#include <__chrono/time_point.h>
54#include <__config>
55#include <__thread/poll_with_backoff.h>
56#include <__thread/timed_backoff_policy.h>
57#include <__threading_support>
58#include <cstddef>
59#include <limits>
60#include <version>
61
62#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
63#  pragma GCC system_header
64#endif
65
66#ifdef _LIBCPP_HAS_NO_THREADS
67#  error "<semaphore> is not supported since libc++ has been configured without support for threads."
68#endif
69
70_LIBCPP_PUSH_MACROS
71#include <__undef_macros>
72
73#if _LIBCPP_STD_VER >= 14
74
75_LIBCPP_BEGIN_NAMESPACE_STD
76
77/*
78
79__atomic_semaphore_base is the general-case implementation.
80It is a typical Dijkstra semaphore algorithm over atomics, wait and notify
81functions. It avoids contention against users' own use of those facilities.
82
83*/
84
85#  define _LIBCPP_SEMAPHORE_MAX (numeric_limits<ptrdiff_t>::max())
86
87class __atomic_semaphore_base {
88  __atomic_base<ptrdiff_t> __a_;
89
90public:
91  _LIBCPP_HIDE_FROM_ABI constexpr explicit __atomic_semaphore_base(ptrdiff_t __count) : __a_(__count) {}
92  _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI void release(ptrdiff_t __update = 1) {
93    auto __old = __a_.fetch_add(__update, memory_order_release);
94    _LIBCPP_ASSERT_UNCATEGORIZED(
95        __update <= _LIBCPP_SEMAPHORE_MAX - __old, "update is greater than the expected value");
96
97    if (__old > 0) {
98      // Nothing to do
99    } else if (__update > 1)
100      __a_.notify_all();
101    else
102      __a_.notify_one();
103  }
104  _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI void acquire() {
105    auto const __test_fn = [this]() -> bool {
106      auto __old = __a_.load(memory_order_relaxed);
107      return (__old != 0) && __a_.compare_exchange_strong(__old, __old - 1, memory_order_acquire, memory_order_relaxed);
108    };
109    __cxx_atomic_wait(&__a_.__a_, __test_fn);
110  }
111  template <class _Rep, class _Period>
112  _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI bool
113  try_acquire_for(chrono::duration<_Rep, _Period> const& __rel_time) {
114    if (__rel_time == chrono::duration<_Rep, _Period>::zero())
115      return try_acquire();
116    auto const __test_fn = [this]() { return try_acquire(); };
117    return std::__libcpp_thread_poll_with_backoff(__test_fn, __libcpp_timed_backoff_policy(), __rel_time);
118  }
119  _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI bool try_acquire() {
120    auto __old = __a_.load(memory_order_acquire);
121    while (true) {
122      if (__old == 0)
123        return false;
124      if (__a_.compare_exchange_strong(__old, __old - 1, memory_order_acquire, memory_order_relaxed))
125        return true;
126    }
127  }
128};
129
130template <ptrdiff_t __least_max_value = _LIBCPP_SEMAPHORE_MAX>
131class counting_semaphore {
132  __atomic_semaphore_base __semaphore_;
133
134public:
135  static_assert(__least_max_value >= 0, "The least maximum value must be a positive number");
136
137  static constexpr ptrdiff_t max() noexcept { return __least_max_value; }
138
139  _LIBCPP_HIDE_FROM_ABI constexpr explicit counting_semaphore(ptrdiff_t __count) : __semaphore_(__count) {
140    _LIBCPP_ASSERT_UNCATEGORIZED(
141        __count >= 0,
142        "counting_semaphore::counting_semaphore(ptrdiff_t): counting_semaphore cannot be "
143        "initialized with a negative value");
144    _LIBCPP_ASSERT_UNCATEGORIZED(
145        __count <= max(),
146        "counting_semaphore::counting_semaphore(ptrdiff_t): counting_semaphore cannot be "
147        "initialized with a value greater than max()");
148  }
149  ~counting_semaphore() = default;
150
151  counting_semaphore(const counting_semaphore&)            = delete;
152  counting_semaphore& operator=(const counting_semaphore&) = delete;
153
154  _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI void release(ptrdiff_t __update = 1) {
155    _LIBCPP_ASSERT_UNCATEGORIZED(__update >= 0, "counting_semaphore:release called with a negative value");
156    __semaphore_.release(__update);
157  }
158  _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI void acquire() { __semaphore_.acquire(); }
159  template <class _Rep, class _Period>
160  _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI bool
161  try_acquire_for(chrono::duration<_Rep, _Period> const& __rel_time) {
162    return __semaphore_.try_acquire_for(chrono::duration_cast<chrono::nanoseconds>(__rel_time));
163  }
164  _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI bool try_acquire() { return __semaphore_.try_acquire(); }
165  template <class _Clock, class _Duration>
166  _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI bool
167  try_acquire_until(chrono::time_point<_Clock, _Duration> const& __abs_time) {
168    auto const __current = _Clock::now();
169    if (__current >= __abs_time)
170      return try_acquire();
171    else
172      return try_acquire_for(__abs_time - __current);
173  }
174};
175
176using binary_semaphore = counting_semaphore<1>;
177
178_LIBCPP_END_NAMESPACE_STD
179
180#endif // _LIBCPP_STD_VER >= 14
181
182_LIBCPP_POP_MACROS
183
184#if !defined(_LIBCPP_REMOVE_TRANSITIVE_INCLUDES) && _LIBCPP_STD_VER <= 20
185#  include <atomic>
186#endif
187
188#endif //_LIBCPP_SEMAPHORE
189