xref: /freebsd/contrib/llvm-project/libcxx/include/condition_variable (revision 7a6dacaca14b62ca4b74406814becb87a3fefac0)
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_CONDITION_VARIABLE
11#define _LIBCPP_CONDITION_VARIABLE
12
13/*
14    condition_variable synopsis
15
16namespace std
17{
18
19enum class cv_status { no_timeout, timeout };
20
21class condition_variable
22{
23public:
24    condition_variable();
25    ~condition_variable();
26
27    condition_variable(const condition_variable&) = delete;
28    condition_variable& operator=(const condition_variable&) = delete;
29
30    void notify_one() noexcept;
31    void notify_all() noexcept;
32
33    void wait(unique_lock<mutex>& lock);
34    template <class Predicate>
35        void wait(unique_lock<mutex>& lock, Predicate pred);
36
37    template <class Clock, class Duration>
38        cv_status
39        wait_until(unique_lock<mutex>& lock,
40                   const chrono::time_point<Clock, Duration>& abs_time);
41
42    template <class Clock, class Duration, class Predicate>
43        bool
44        wait_until(unique_lock<mutex>& lock,
45                   const chrono::time_point<Clock, Duration>& abs_time,
46                   Predicate pred);
47
48    template <class Rep, class Period>
49        cv_status
50        wait_for(unique_lock<mutex>& lock,
51                 const chrono::duration<Rep, Period>& rel_time);
52
53    template <class Rep, class Period, class Predicate>
54        bool
55        wait_for(unique_lock<mutex>& lock,
56                 const chrono::duration<Rep, Period>& rel_time,
57                 Predicate pred);
58
59    typedef pthread_cond_t* native_handle_type;
60    native_handle_type native_handle();
61};
62
63void notify_all_at_thread_exit(condition_variable& cond, unique_lock<mutex> lk);
64
65class condition_variable_any
66{
67public:
68    condition_variable_any();
69    ~condition_variable_any();
70
71    condition_variable_any(const condition_variable_any&) = delete;
72    condition_variable_any& operator=(const condition_variable_any&) = delete;
73
74    void notify_one() noexcept;
75    void notify_all() noexcept;
76
77    template <class Lock>
78        void wait(Lock& lock);
79    template <class Lock, class Predicate>
80        void wait(Lock& lock, Predicate pred);
81
82    template <class Lock, class Clock, class Duration>
83        cv_status
84        wait_until(Lock& lock,
85                   const chrono::time_point<Clock, Duration>& abs_time);
86
87    template <class Lock, class Clock, class Duration, class Predicate>
88        bool
89        wait_until(Lock& lock,
90                   const chrono::time_point<Clock, Duration>& abs_time,
91                   Predicate pred);
92
93    template <class Lock, class Rep, class Period>
94        cv_status
95        wait_for(Lock& lock,
96                 const chrono::duration<Rep, Period>& rel_time);
97
98    template <class Lock, class Rep, class Period, class Predicate>
99        bool
100        wait_for(Lock& lock,
101                 const chrono::duration<Rep, Period>& rel_time,
102                 Predicate pred);
103
104    // [thread.condvarany.intwait], interruptible waits
105    template <class Lock, class Predicate>
106      bool wait(Lock& lock, stop_token stoken, Predicate pred);                               // since C++20
107
108    template <class Lock, class Clock, class Duration, class Predicate>
109      bool wait_until(Lock& lock, stop_token stoken,
110                      const chrono::time_point<Clock, Duration>& abs_time, Predicate pred);   // since C++20
111
112    template <class Lock, class Rep, class Period, class Predicate>
113      bool wait_for(Lock& lock, stop_token stoken,
114                    const chrono::duration<Rep, Period>& rel_time, Predicate pred);           // since C++20
115};
116
117}  // std
118
119*/
120
121#include <__assert> // all public C++ headers provide the assertion handler
122#include <__availability>
123#include <__chrono/duration.h>
124#include <__chrono/steady_clock.h>
125#include <__chrono/time_point.h>
126#include <__condition_variable/condition_variable.h>
127#include <__config>
128#include <__memory/shared_ptr.h>
129#include <__mutex/lock_guard.h>
130#include <__mutex/mutex.h>
131#include <__mutex/tag_types.h>
132#include <__mutex/unique_lock.h>
133#include <__stop_token/stop_callback.h>
134#include <__stop_token/stop_token.h>
135#include <__utility/move.h>
136#include <version>
137
138#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
139#  pragma GCC system_header
140#endif
141
142#ifndef _LIBCPP_HAS_NO_THREADS
143
144_LIBCPP_BEGIN_NAMESPACE_STD
145
146class _LIBCPP_EXPORTED_FROM_ABI condition_variable_any {
147  condition_variable __cv_;
148  shared_ptr<mutex> __mut_;
149
150public:
151  _LIBCPP_HIDE_FROM_ABI condition_variable_any();
152
153  _LIBCPP_HIDE_FROM_ABI void notify_one() _NOEXCEPT;
154  _LIBCPP_HIDE_FROM_ABI void notify_all() _NOEXCEPT;
155
156  template <class _Lock>
157  _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS void wait(_Lock& __lock);
158  template <class _Lock, class _Predicate>
159  _LIBCPP_HIDE_FROM_ABI void wait(_Lock& __lock, _Predicate __pred);
160
161  template <class _Lock, class _Clock, class _Duration>
162  _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS cv_status
163  wait_until(_Lock& __lock, const chrono::time_point<_Clock, _Duration>& __t);
164
165  template <class _Lock, class _Clock, class _Duration, class _Predicate>
166  bool _LIBCPP_HIDE_FROM_ABI
167  wait_until(_Lock& __lock, const chrono::time_point<_Clock, _Duration>& __t, _Predicate __pred);
168
169  template <class _Lock, class _Rep, class _Period>
170  cv_status _LIBCPP_HIDE_FROM_ABI wait_for(_Lock& __lock, const chrono::duration<_Rep, _Period>& __d);
171
172  template <class _Lock, class _Rep, class _Period, class _Predicate>
173  bool _LIBCPP_HIDE_FROM_ABI wait_for(_Lock& __lock, const chrono::duration<_Rep, _Period>& __d, _Predicate __pred);
174
175#  if _LIBCPP_STD_VER >= 20 && !defined(_LIBCPP_HAS_NO_EXPERIMENTAL_STOP_TOKEN)
176
177  template <class _Lock, class _Predicate>
178  _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI bool wait(_Lock& __lock, stop_token __stoken, _Predicate __pred);
179
180  template <class _Lock, class _Clock, class _Duration, class _Predicate>
181  _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI bool wait_until(
182      _Lock& __lock, stop_token __stoken, const chrono::time_point<_Clock, _Duration>& __abs_time, _Predicate __pred);
183
184  template <class _Lock, class _Rep, class _Period, class _Predicate>
185  _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI bool
186  wait_for(_Lock& __lock, stop_token __stoken, const chrono::duration<_Rep, _Period>& __rel_time, _Predicate __pred);
187
188#  endif // _LIBCPP_STD_VER >= 20 && !defined(_LIBCPP_HAS_NO_EXPERIMENTAL_STOP_TOKEN)
189};
190
191inline condition_variable_any::condition_variable_any() : __mut_(make_shared<mutex>()) {}
192
193inline void condition_variable_any::notify_one() _NOEXCEPT {
194  { lock_guard<mutex> __lx(*__mut_); }
195  __cv_.notify_one();
196}
197
198inline void condition_variable_any::notify_all() _NOEXCEPT {
199  { lock_guard<mutex> __lx(*__mut_); }
200  __cv_.notify_all();
201}
202
203template <class _Lock>
204struct __unlock_guard {
205  _Lock& __lock_;
206
207  _LIBCPP_HIDE_FROM_ABI __unlock_guard(_Lock& __lock) : __lock_(__lock) { __lock_.unlock(); }
208
209  _LIBCPP_HIDE_FROM_ABI ~__unlock_guard() _NOEXCEPT // turns exception to std::terminate
210  {
211    __lock_.lock();
212  }
213
214  __unlock_guard(const __unlock_guard&)            = delete;
215  __unlock_guard& operator=(const __unlock_guard&) = delete;
216};
217
218template <class _Lock>
219void condition_variable_any::wait(_Lock& __lock) {
220  shared_ptr<mutex> __mut = __mut_;
221  unique_lock<mutex> __lk(*__mut);
222  __unlock_guard<_Lock> __unlock(__lock);
223  lock_guard<unique_lock<mutex> > __lx(__lk, adopt_lock_t());
224  __cv_.wait(__lk);
225} // __mut_.unlock(), __lock.lock()
226
227template <class _Lock, class _Predicate>
228inline void condition_variable_any::wait(_Lock& __lock, _Predicate __pred) {
229  while (!__pred())
230    wait(__lock);
231}
232
233template <class _Lock, class _Clock, class _Duration>
234cv_status condition_variable_any::wait_until(_Lock& __lock, const chrono::time_point<_Clock, _Duration>& __t) {
235  shared_ptr<mutex> __mut = __mut_;
236  unique_lock<mutex> __lk(*__mut);
237  __unlock_guard<_Lock> __unlock(__lock);
238  lock_guard<unique_lock<mutex> > __lx(__lk, adopt_lock_t());
239  return __cv_.wait_until(__lk, __t);
240} // __mut_.unlock(), __lock.lock()
241
242template <class _Lock, class _Clock, class _Duration, class _Predicate>
243inline bool
244condition_variable_any::wait_until(_Lock& __lock, const chrono::time_point<_Clock, _Duration>& __t, _Predicate __pred) {
245  while (!__pred())
246    if (wait_until(__lock, __t) == cv_status::timeout)
247      return __pred();
248  return true;
249}
250
251template <class _Lock, class _Rep, class _Period>
252inline cv_status condition_variable_any::wait_for(_Lock& __lock, const chrono::duration<_Rep, _Period>& __d) {
253  return wait_until(__lock, chrono::steady_clock::now() + __d);
254}
255
256template <class _Lock, class _Rep, class _Period, class _Predicate>
257inline bool
258condition_variable_any::wait_for(_Lock& __lock, const chrono::duration<_Rep, _Period>& __d, _Predicate __pred) {
259  return wait_until(__lock, chrono::steady_clock::now() + __d, std::move(__pred));
260}
261
262#  if _LIBCPP_STD_VER >= 20 && !defined(_LIBCPP_HAS_NO_EXPERIMENTAL_STOP_TOKEN)
263
264template <class _Lock, class _Predicate>
265bool condition_variable_any::wait(_Lock& __user_lock, stop_token __stoken, _Predicate __pred) {
266  if (__stoken.stop_requested())
267    return __pred();
268
269  // Per https://eel.is/c++draft/thread.condition.condvarany#general-note-2,
270  // we do need to take a copy of the shared pointer __mut_
271  // This ensures that a thread can call the destructor immediately after calling
272  // notify_all, without waiting all the wait calls.
273  // A thread can also safely call the destructor immediately after calling
274  // request_stop, as the call to request_stop would evaluate the callback,
275  // which accesses the internal condition variable, immediately on the same thread.
276  // In this situation, it is OK even without copying a shared ownership the internal
277  // condition variable. However, this needs the evaluation of stop_callback to
278  // happen-before the destruction.
279  // The spec only says "Only the notification to unblock the wait needs to happen
280  // before destruction". To make this work, we need to copy the shared ownership of
281  // the internal condition variable inside this function, which is not possible
282  // with the current ABI.
283  shared_ptr<mutex> __mut = __mut_;
284
285  stop_callback __cb(__stoken, [this] { notify_all(); });
286
287  while (true) {
288    if (__pred())
289      return true;
290
291    // We need to take the internal lock before checking stop_requested,
292    // so that the notification cannot come in between the stop_requested
293    // check and entering the wait.
294    // Note that the stop_callback takes the same internal lock before notifying
295    unique_lock<mutex> __internal_lock(*__mut);
296    if (__stoken.stop_requested())
297      break;
298
299    __unlock_guard<_Lock> __unlock(__user_lock);
300    unique_lock<mutex> __internal_lock2(
301        std::move(__internal_lock)); // switch unlock order between __internal_lock and __user_lock
302    __cv_.wait(__internal_lock2);
303  } // __internal_lock2.unlock(), __user_lock.lock()
304  return __pred();
305}
306
307template <class _Lock, class _Clock, class _Duration, class _Predicate>
308bool condition_variable_any::wait_until(
309    _Lock& __user_lock,
310    stop_token __stoken,
311    const chrono::time_point<_Clock, _Duration>& __abs_time,
312    _Predicate __pred) {
313  if (__stoken.stop_requested())
314    return __pred();
315
316  shared_ptr<mutex> __mut = __mut_;
317  stop_callback __cb(__stoken, [this] { notify_all(); });
318
319  while (true) {
320    if (__pred())
321      return true;
322
323    unique_lock<mutex> __internal_lock(*__mut);
324    if (__stoken.stop_requested())
325      break;
326
327    __unlock_guard<_Lock> __unlock(__user_lock);
328    unique_lock<mutex> __internal_lock2(
329        std::move(__internal_lock)); // switch unlock order between __internal_lock and __user_lock
330
331    if (__cv_.wait_until(__internal_lock2, __abs_time) == cv_status::timeout)
332      break;
333  } // __internal_lock2.unlock(), __user_lock.lock()
334  return __pred();
335}
336
337template <class _Lock, class _Rep, class _Period, class _Predicate>
338bool condition_variable_any::wait_for(
339    _Lock& __lock, stop_token __stoken, const chrono::duration<_Rep, _Period>& __rel_time, _Predicate __pred) {
340  return wait_until(__lock, std::move(__stoken), chrono::steady_clock::now() + __rel_time, std::move(__pred));
341}
342
343#  endif // _LIBCPP_STD_VER >= 20 && !defined(_LIBCPP_HAS_NO_EXPERIMENTAL_STOP_TOKEN)
344
345_LIBCPP_EXPORTED_FROM_ABI void notify_all_at_thread_exit(condition_variable&, unique_lock<mutex>);
346
347_LIBCPP_END_NAMESPACE_STD
348
349#endif // !_LIBCPP_HAS_NO_THREADS
350
351#if !defined(_LIBCPP_REMOVE_TRANSITIVE_INCLUDES) && _LIBCPP_STD_VER <= 20
352#  include <atomic>
353#  include <concepts>
354#  include <cstdint>
355#  include <cstdlib>
356#  include <cstring>
357#  include <initializer_list>
358#  include <iosfwd>
359#  include <new>
360#  include <stdexcept>
361#  include <system_error>
362#  include <type_traits>
363#  include <typeinfo>
364#endif
365
366#endif // _LIBCPP_CONDITION_VARIABLE
367