xref: /llvm-project/libcxx/include/condition_variable (revision b9a2658a3e8bd13b0f9e7a8a440832a95b377216)
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#if __cplusplus < 201103L && defined(_LIBCPP_USE_FROZEN_CXX03_HEADERS)
122#  include <__cxx03/condition_variable>
123#else
124#  include <__chrono/duration.h>
125#  include <__chrono/steady_clock.h>
126#  include <__chrono/time_point.h>
127#  include <__condition_variable/condition_variable.h>
128#  include <__config>
129#  include <__memory/shared_ptr.h>
130#  include <__mutex/lock_guard.h>
131#  include <__mutex/mutex.h>
132#  include <__mutex/tag_types.h>
133#  include <__mutex/unique_lock.h>
134#  include <__stop_token/stop_callback.h>
135#  include <__stop_token/stop_token.h>
136#  include <__utility/move.h>
137#  include <version>
138
139#  if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
140#    pragma GCC system_header
141#  endif
142
143_LIBCPP_PUSH_MACROS
144#  include <__undef_macros>
145
146#  if _LIBCPP_HAS_THREADS
147
148_LIBCPP_BEGIN_NAMESPACE_STD
149
150class _LIBCPP_EXPORTED_FROM_ABI condition_variable_any {
151  condition_variable __cv_;
152  shared_ptr<mutex> __mut_;
153
154public:
155  _LIBCPP_HIDE_FROM_ABI condition_variable_any();
156
157  _LIBCPP_HIDE_FROM_ABI void notify_one() _NOEXCEPT;
158  _LIBCPP_HIDE_FROM_ABI void notify_all() _NOEXCEPT;
159
160  template <class _Lock>
161  _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS void wait(_Lock& __lock);
162  template <class _Lock, class _Predicate>
163  _LIBCPP_HIDE_FROM_ABI void wait(_Lock& __lock, _Predicate __pred);
164
165  template <class _Lock, class _Clock, class _Duration>
166  _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS cv_status
167  wait_until(_Lock& __lock, const chrono::time_point<_Clock, _Duration>& __t);
168
169  template <class _Lock, class _Clock, class _Duration, class _Predicate>
170  bool _LIBCPP_HIDE_FROM_ABI
171  wait_until(_Lock& __lock, const chrono::time_point<_Clock, _Duration>& __t, _Predicate __pred);
172
173  template <class _Lock, class _Rep, class _Period>
174  cv_status _LIBCPP_HIDE_FROM_ABI wait_for(_Lock& __lock, const chrono::duration<_Rep, _Period>& __d);
175
176  template <class _Lock, class _Rep, class _Period, class _Predicate>
177  bool _LIBCPP_HIDE_FROM_ABI wait_for(_Lock& __lock, const chrono::duration<_Rep, _Period>& __d, _Predicate __pred);
178
179#    if _LIBCPP_STD_VER >= 20
180
181  template <class _Lock, class _Predicate>
182  _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI bool wait(_Lock& __lock, stop_token __stoken, _Predicate __pred);
183
184  template <class _Lock, class _Clock, class _Duration, class _Predicate>
185  _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI bool wait_until(
186      _Lock& __lock, stop_token __stoken, const chrono::time_point<_Clock, _Duration>& __abs_time, _Predicate __pred);
187
188  template <class _Lock, class _Rep, class _Period, class _Predicate>
189  _LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI bool
190  wait_for(_Lock& __lock, stop_token __stoken, const chrono::duration<_Rep, _Period>& __rel_time, _Predicate __pred);
191
192#    endif // _LIBCPP_STD_VER >= 20
193};
194
195inline condition_variable_any::condition_variable_any() : __mut_(make_shared<mutex>()) {}
196
197inline void condition_variable_any::notify_one() _NOEXCEPT {
198  { lock_guard<mutex> __lx(*__mut_); }
199  __cv_.notify_one();
200}
201
202inline void condition_variable_any::notify_all() _NOEXCEPT {
203  { lock_guard<mutex> __lx(*__mut_); }
204  __cv_.notify_all();
205}
206
207template <class _Lock>
208struct __unlock_guard {
209  _Lock& __lock_;
210
211  _LIBCPP_HIDE_FROM_ABI __unlock_guard(_Lock& __lock) : __lock_(__lock) { __lock_.unlock(); }
212
213  _LIBCPP_HIDE_FROM_ABI ~__unlock_guard() _NOEXCEPT // turns exception to std::terminate
214  {
215    __lock_.lock();
216  }
217
218  __unlock_guard(const __unlock_guard&)            = delete;
219  __unlock_guard& operator=(const __unlock_guard&) = delete;
220};
221
222template <class _Lock>
223void condition_variable_any::wait(_Lock& __lock) {
224  shared_ptr<mutex> __mut = __mut_;
225  unique_lock<mutex> __lk(*__mut);
226  __unlock_guard<_Lock> __unlock(__lock);
227  lock_guard<unique_lock<mutex> > __lx(__lk, adopt_lock_t());
228  __cv_.wait(__lk);
229} // __mut_.unlock(), __lock.lock()
230
231template <class _Lock, class _Predicate>
232inline void condition_variable_any::wait(_Lock& __lock, _Predicate __pred) {
233  while (!__pred())
234    wait(__lock);
235}
236
237template <class _Lock, class _Clock, class _Duration>
238cv_status condition_variable_any::wait_until(_Lock& __lock, const chrono::time_point<_Clock, _Duration>& __t) {
239  shared_ptr<mutex> __mut = __mut_;
240  unique_lock<mutex> __lk(*__mut);
241  __unlock_guard<_Lock> __unlock(__lock);
242  lock_guard<unique_lock<mutex> > __lx(__lk, adopt_lock_t());
243  return __cv_.wait_until(__lk, __t);
244} // __mut_.unlock(), __lock.lock()
245
246template <class _Lock, class _Clock, class _Duration, class _Predicate>
247inline bool
248condition_variable_any::wait_until(_Lock& __lock, const chrono::time_point<_Clock, _Duration>& __t, _Predicate __pred) {
249  while (!__pred())
250    if (wait_until(__lock, __t) == cv_status::timeout)
251      return __pred();
252  return true;
253}
254
255template <class _Lock, class _Rep, class _Period>
256inline cv_status condition_variable_any::wait_for(_Lock& __lock, const chrono::duration<_Rep, _Period>& __d) {
257  return wait_until(__lock, chrono::steady_clock::now() + __d);
258}
259
260template <class _Lock, class _Rep, class _Period, class _Predicate>
261inline bool
262condition_variable_any::wait_for(_Lock& __lock, const chrono::duration<_Rep, _Period>& __d, _Predicate __pred) {
263  return wait_until(__lock, chrono::steady_clock::now() + __d, std::move(__pred));
264}
265
266#    if _LIBCPP_STD_VER >= 20
267
268template <class _Lock, class _Predicate>
269bool condition_variable_any::wait(_Lock& __user_lock, stop_token __stoken, _Predicate __pred) {
270  if (__stoken.stop_requested())
271    return __pred();
272
273  // Per https://eel.is/c++draft/thread.condition.condvarany#general-note-2,
274  // we do need to take a copy of the shared pointer __mut_
275  // This ensures that a thread can call the destructor immediately after calling
276  // notify_all, without waiting all the wait calls.
277  // A thread can also safely call the destructor immediately after calling
278  // request_stop, as the call to request_stop would evaluate the callback,
279  // which accesses the internal condition variable, immediately on the same thread.
280  // In this situation, it is OK even without copying a shared ownership the internal
281  // condition variable. However, this needs the evaluation of stop_callback to
282  // happen-before the destruction.
283  // The spec only says "Only the notification to unblock the wait needs to happen
284  // before destruction". To make this work, we need to copy the shared ownership of
285  // the internal condition variable inside this function, which is not possible
286  // with the current ABI.
287  shared_ptr<mutex> __mut = __mut_;
288
289  stop_callback __cb(__stoken, [this] { notify_all(); });
290
291  while (true) {
292    if (__pred())
293      return true;
294
295    // We need to take the internal lock before checking stop_requested,
296    // so that the notification cannot come in between the stop_requested
297    // check and entering the wait.
298    // Note that the stop_callback takes the same internal lock before notifying
299    unique_lock<mutex> __internal_lock(*__mut);
300    if (__stoken.stop_requested())
301      break;
302
303    __unlock_guard<_Lock> __unlock(__user_lock);
304    unique_lock<mutex> __internal_lock2(
305        std::move(__internal_lock)); // switch unlock order between __internal_lock and __user_lock
306    __cv_.wait(__internal_lock2);
307  } // __internal_lock2.unlock(), __user_lock.lock()
308  return __pred();
309}
310
311template <class _Lock, class _Clock, class _Duration, class _Predicate>
312bool condition_variable_any::wait_until(
313    _Lock& __user_lock,
314    stop_token __stoken,
315    const chrono::time_point<_Clock, _Duration>& __abs_time,
316    _Predicate __pred) {
317  if (__stoken.stop_requested())
318    return __pred();
319
320  shared_ptr<mutex> __mut = __mut_;
321  stop_callback __cb(__stoken, [this] { notify_all(); });
322
323  while (true) {
324    if (__pred())
325      return true;
326
327    unique_lock<mutex> __internal_lock(*__mut);
328    if (__stoken.stop_requested())
329      break;
330
331    __unlock_guard<_Lock> __unlock(__user_lock);
332    unique_lock<mutex> __internal_lock2(
333        std::move(__internal_lock)); // switch unlock order between __internal_lock and __user_lock
334
335    if (__cv_.wait_until(__internal_lock2, __abs_time) == cv_status::timeout)
336      break;
337  } // __internal_lock2.unlock(), __user_lock.lock()
338  return __pred();
339}
340
341template <class _Lock, class _Rep, class _Period, class _Predicate>
342bool condition_variable_any::wait_for(
343    _Lock& __lock, stop_token __stoken, const chrono::duration<_Rep, _Period>& __rel_time, _Predicate __pred) {
344  return wait_until(__lock, std::move(__stoken), chrono::steady_clock::now() + __rel_time, std::move(__pred));
345}
346
347#    endif // _LIBCPP_STD_VER >= 20
348
349_LIBCPP_EXPORTED_FROM_ABI void notify_all_at_thread_exit(condition_variable&, unique_lock<mutex>);
350
351_LIBCPP_END_NAMESPACE_STD
352
353#  endif // _LIBCPP_HAS_THREADS
354
355_LIBCPP_POP_MACROS
356
357#  if !defined(_LIBCPP_REMOVE_TRANSITIVE_INCLUDES) && _LIBCPP_STD_VER <= 20
358#    include <atomic>
359#    include <concepts>
360#    include <cstdint>
361#    include <cstdlib>
362#    include <cstring>
363#    include <initializer_list>
364#    include <iosfwd>
365#    include <new>
366#    include <stdexcept>
367#    include <system_error>
368#    include <type_traits>
369#    include <typeinfo>
370#  endif
371#endif // __cplusplus < 201103L && defined(_LIBCPP_USE_FROZEN_CXX03_HEADERS)
372
373#endif // _LIBCPP_CONDITION_VARIABLE
374