libstdc++: condition_variable Source File

libstdc++

condition_variable
Go to the documentation of this file.
1// <condition_variable> -*- C++ -*-
2
3// Copyright (C) 2008-2026 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/** @file include/condition_variable
26 * This is a Standard C++ Library header.
27 */
28
29#ifndef _GLIBCXX_CONDITION_VARIABLE
30#define _GLIBCXX_CONDITION_VARIABLE 1
31
32#ifdef _GLIBCXX_SYSHDR
33#pragma GCC system_header
34#endif
35
36#include <bits/requires_hosted.h> // threading primitive
37
38#if __cplusplus < 201103L
39# include <bits/c++0x_warning.h>
40#else
41
42#include <bits/chrono.h>
43#include <bits/error_constants.h>
44#include <bits/std_mutex.h>
45#include <bits/unique_lock.h>
46#include <bits/alloc_traits.h>
47#include <bits/shared_ptr.h>
48#include <bits/cxxabi_forced.h>
49
50#if __cplusplus > 201703L
51# include <stop_token>
52#endif
53
54#if defined(_GLIBCXX_HAS_GTHREADS)
55
56namespace std _GLIBCXX_VISIBILITY(default)
57{
58_GLIBCXX_BEGIN_NAMESPACE_VERSION
59
60 /**
61 * @defgroup condition_variables Condition Variables
62 * @ingroup concurrency
63 *
64 * Classes for condition_variable support.
65 * @{
66 */
67
68 /// cv_status
69 enum class cv_status { no_timeout, timeout };
70
71 /// condition_variable
72 class condition_variable
73 {
74 using steady_clock = chrono::steady_clock;
75 using system_clock = chrono::system_clock;
76#ifdef _GLIBCXX_USE_PTHREAD_COND_CLOCKWAIT
77 using __clock_t = steady_clock;
78#else
79 using __clock_t = system_clock;
80#endif
81
82 __condvar _M_cond;
83
84 public:
85 typedef __gthread_cond_t* native_handle_type;
86
87 condition_variable() noexcept;
88 ~condition_variable() noexcept;
89
90 condition_variable(const condition_variable&) = delete;
91 condition_variable& operator=(const condition_variable&) = delete;
92
93 void
94 notify_one() noexcept;
95
96 void
97 notify_all() noexcept;
98
99 void
100 wait(unique_lock<mutex>& __lock);
101
102 template<typename _Predicate>
103 void
104 wait(unique_lock<mutex>& __lock, _Predicate __p)
105 {
106 while (!__p())
107 wait(__lock);
108 }
109
110 // _GLIBCXX_RESOLVE_LIB_DEFECTS
111 // 4301. condition_variable{_any}::wait_{for, until} should take timeout by value
112
113#ifdef _GLIBCXX_USE_PTHREAD_COND_CLOCKWAIT
114 template<typename _Duration>
115 cv_status
116 wait_until(unique_lock<mutex>& __lock,
117 chrono::time_point<steady_clock, _Duration> __atime)
118 { return __wait_until_impl(__lock, __atime); }
119#endif
120
121 template<typename _Duration>
122 cv_status
123 wait_until(unique_lock<mutex>& __lock,
124 chrono::time_point<system_clock, _Duration> __atime)
125 { return __wait_until_impl(__lock, __atime); }
126
127 template<typename _Clock, typename _Duration>
128 cv_status
129 wait_until(unique_lock<mutex>& __lock,
130 chrono::time_point<_Clock, _Duration> __atime)
131 {
132#if __cplusplus > 201703L
133 static_assert(chrono::is_clock_v<_Clock>);
134#endif
135 using __s_dur = typename __clock_t::duration;
136 const typename _Clock::time_point __c_entry = _Clock::now();
137 const __clock_t::time_point __s_entry = __clock_t::now();
138 const auto __delta = __atime - __c_entry;
139 const auto __s_atime = __s_entry +
140 chrono::__detail::ceil<__s_dur>(__delta);
141
142 if (__wait_until_impl(__lock, __s_atime) == cv_status::no_timeout)
143 return cv_status::no_timeout;
144 // We got a timeout when measured against __clock_t but
145 // we need to check against the caller-supplied clock
146 // to tell whether we should return a timeout.
147 if (_Clock::now() < __atime)
148 return cv_status::no_timeout;
149 return cv_status::timeout;
150 }
151
152 template<typename _Clock, typename _Duration, typename _Predicate>
153 bool
154 wait_until(unique_lock<mutex>& __lock,
155 chrono::time_point<_Clock, _Duration> __atime,
156 _Predicate __p)
157 {
158 while (!__p())
159 if (wait_until(__lock, __atime) == cv_status::timeout)
160 return __p();
161 return true;
162 }
163
164 template<typename _Rep, typename _Period>
165 cv_status
166 wait_for(unique_lock<mutex>& __lock,
167 chrono::duration<_Rep, _Period> __rtime)
168 {
169 // _GLIBCXX_RESOLVE_LIB_DEFECTS
170 // 3504. condition_variable::wait_for is overspecified
171 using __dur = typename steady_clock::duration;
172 return wait_until(__lock,
173 steady_clock::now() +
174 chrono::__detail::ceil<__dur>(__rtime));
175 }
176
177 template<typename _Rep, typename _Period, typename _Predicate>
178 bool
179 wait_for(unique_lock<mutex>& __lock,
180 chrono::duration<_Rep, _Period> __rtime,
181 _Predicate __p)
182 {
183 using __dur = typename steady_clock::duration;
184 return wait_until(__lock,
185 steady_clock::now() +
186 chrono::__detail::ceil<__dur>(__rtime),
187 std::move(__p));
188 }
189
190 native_handle_type
191 native_handle()
192 { return _M_cond.native_handle(); }
193
194 private:
195#ifdef _GLIBCXX_USE_PTHREAD_COND_CLOCKWAIT
196 template<typename _Dur>
197 cv_status
198 __wait_until_impl(unique_lock<mutex>& __lock,
199 chrono::time_point<steady_clock, _Dur> __atime)
200 {
201 __gthread_time_t __ts = chrono::__to_timeout_gthread_time_t(__atime);
202 _M_cond.wait_until(*__lock.mutex(), CLOCK_MONOTONIC, __ts);
203
204 return (steady_clock::now() < __atime
205 ? cv_status::no_timeout : cv_status::timeout);
206 }
207#endif
208
209 template<typename _Dur>
210 cv_status
211 __wait_until_impl(unique_lock<mutex>& __lock,
212 chrono::time_point<system_clock, _Dur> __atime)
213 {
214 __gthread_time_t __ts = chrono::__to_timeout_gthread_time_t(__atime);
215 _M_cond.wait_until(*__lock.mutex(), __ts);
216
217 return (system_clock::now() < __atime
218 ? cv_status::no_timeout : cv_status::timeout);
219 }
220 };
221
222 void
223 notify_all_at_thread_exit(condition_variable&, unique_lock<mutex>);
224
225 struct __at_thread_exit_elt
226 {
227 __at_thread_exit_elt* _M_next;
228 void (*_M_cb)(void*);
229 };
230
231_GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(_V2)
232
233 /// condition_variable_any
234 // Like above, but mutex is not required to have try_lock.
235 class condition_variable_any
236 {
237#ifdef _GLIBCXX_USE_PTHREAD_COND_CLOCKWAIT
238 using __clock_t = chrono::steady_clock;
239#else
240 using __clock_t = chrono::system_clock;
241#endif
242 condition_variable _M_cond;
243 shared_ptr<mutex> _M_mutex;
244
245 // scoped unlock - unlocks in ctor, re-locks in dtor
246 template<typename _Lock>
247 struct _Unlock
248 {
249 explicit _Unlock(_Lock& __lk) : _M_lock(__lk) { __lk.unlock(); }
250
251#pragma GCC diagnostic push
252#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
253 ~_Unlock() noexcept(false)
254 {
255 if (uncaught_exception())
256 {
257 __try
258 { _M_lock.lock(); }
259 __catch(const __cxxabiv1::__forced_unwind&)
260 { __throw_exception_again; }
261 __catch(...)
262 { }
263 }
264 else
265 _M_lock.lock();
266 }
267#pragma GCC diagnostic pop
268
269 _Unlock(const _Unlock&) = delete;
270 _Unlock& operator=(const _Unlock&) = delete;
271
272 _Lock& _M_lock;
273 };
274
275 public:
276 condition_variable_any() : _M_mutex(std::make_shared<mutex>()) { }
277 ~condition_variable_any() = default;
278
279 condition_variable_any(const condition_variable_any&) = delete;
280 condition_variable_any& operator=(const condition_variable_any&) = delete;
281
282 void
283 notify_one() noexcept
284 {
285 lock_guard<mutex> __lock(*_M_mutex);
286 _M_cond.notify_one();
287 }
288
289 void
290 notify_all() noexcept
291 {
292 lock_guard<mutex> __lock(*_M_mutex);
293 _M_cond.notify_all();
294 }
295
296 template<typename _Lock>
297 void
298 wait(_Lock& __lock)
299 {
300 shared_ptr<mutex> __mutex = _M_mutex;
301 unique_lock<mutex> __my_lock(*__mutex);
302 _Unlock<_Lock> __unlock(__lock);
303 // *__mutex must be unlocked before re-locking __lock so move
304 // ownership of *__mutex lock to an object with shorter lifetime.
305 unique_lock<mutex> __my_lock2(std::move(__my_lock));
306 _M_cond.wait(__my_lock2);
307 }
308
309
310 template<typename _Lock, typename _Predicate>
311 void
312 wait(_Lock& __lock, _Predicate __p)
313 {
314 while (!__p())
315 wait(__lock);
316 }
317
318 // _GLIBCXX_RESOLVE_LIB_DEFECTS
319 // 4301. condition_variable{_any}::wait_{for, until} should take timeout by value
320
321 template<typename _Lock, typename _Clock, typename _Duration>
322 cv_status
323 wait_until(_Lock& __lock,
324 chrono::time_point<_Clock, _Duration> __atime)
325 {
326 shared_ptr<mutex> __mutex = _M_mutex;
327 unique_lock<mutex> __my_lock(*__mutex);
328 _Unlock<_Lock> __unlock(__lock);
329 // *__mutex must be unlocked before re-locking __lock so move
330 // ownership of *__mutex lock to an object with shorter lifetime.
331 unique_lock<mutex> __my_lock2(std::move(__my_lock));
332 return _M_cond.wait_until(__my_lock2, __atime);
333 }
334
335 template<typename _Lock, typename _Clock,
336 typename _Duration, typename _Predicate>
337 bool
338 wait_until(_Lock& __lock,
339 chrono::time_point<_Clock, _Duration> __atime,
340 _Predicate __p)
341 {
342 while (!__p())
343 if (wait_until(__lock, __atime) == cv_status::timeout)
344 return __p();
345 return true;
346 }
347
348 template<typename _Lock, typename _Rep, typename _Period>
349 cv_status
350 wait_for(_Lock& __lock, chrono::duration<_Rep, _Period> __rtime)
351 { return wait_until(__lock, __clock_t::now() + __rtime); }
352
353 template<typename _Lock, typename _Rep,
354 typename _Period, typename _Predicate>
355 bool
356 wait_for(_Lock& __lock,
357 chrono::duration<_Rep, _Period> __rtime, _Predicate __p)
358 { return wait_until(__lock, __clock_t::now() + __rtime, std::move(__p)); }
359
360#ifdef __glibcxx_jthread
361 template <class _Lock, class _Predicate>
362 bool wait(_Lock& __lock,
363 stop_token __stoken,
364 _Predicate __p)
365 {
366 if (__stoken.stop_requested())
367 {
368 return __p();
369 }
370
371 std::stop_callback __cb(__stoken, [this] { notify_all(); });
372 shared_ptr<mutex> __mutex = _M_mutex;
373 while (!__p())
374 {
375 unique_lock<mutex> __my_lock(*__mutex);
376 if (__stoken.stop_requested())
377 {
378 return false;
379 }
380 // *__mutex must be unlocked before re-locking __lock so move
381 // ownership of *__mutex lock to an object with shorter lifetime.
382 _Unlock<_Lock> __unlock(__lock);
383 unique_lock<mutex> __my_lock2(std::move(__my_lock));
384 _M_cond.wait(__my_lock2);
385 }
386 return true;
387 }
388
389 template <class _Lock, class _Clock, class _Duration, class _Predicate>
390 bool wait_until(_Lock& __lock,
391 stop_token __stoken,
392 chrono::time_point<_Clock, _Duration> __abs_time,
393 _Predicate __p)
394 {
395 if (__stoken.stop_requested())
396 {
397 return __p();
398 }
399
400 std::stop_callback __cb(__stoken, [this] { notify_all(); });
401 shared_ptr<mutex> __mutex = _M_mutex;
402 while (!__p())
403 {
404 bool __stop;
405 {
406 unique_lock<mutex> __my_lock(*__mutex);
407 if (__stoken.stop_requested())
408 {
409 return false;
410 }
411 _Unlock<_Lock> __u(__lock);
412 unique_lock<mutex> __my_lock2(std::move(__my_lock));
413 const auto __status = _M_cond.wait_until(__my_lock2, __abs_time);
414 __stop = (__status == std::cv_status::timeout) || __stoken.stop_requested();
415 }
416 if (__stop)
417 {
418 return __p();
419 }
420 }
421 return true;
422 }
423
424 template <class _Lock, class _Rep, class _Period, class _Predicate>
425 bool wait_for(_Lock& __lock,
426 stop_token __stoken,
427 chrono::duration<_Rep, _Period> __rel_time,
428 _Predicate __p)
429 {
430 auto __abst = std::chrono::steady_clock::now() + __rel_time;
431 return wait_until(__lock,
432 std::move(__stoken),
433 __abst,
434 std::move(__p));
435 }
436#endif
437 };
438
439_GLIBCXX_END_INLINE_ABI_NAMESPACE(_V2)
440
441 /// @} group condition_variables
442_GLIBCXX_END_NAMESPACE_VERSION
443} // namespace
444
445#endif // _GLIBCXX_HAS_GTHREADS
446#endif // C++11
447#endif // _GLIBCXX_CONDITION_VARIABLE
stop_token
c++0x_warning.h
chrono.h
std::chrono::__detail::ceil
constexpr __enable_if_is_duration< _ToDur > ceil(const duration< _Rep, _Period > &__d)
Definition chrono.h:412
requires_hosted.h
std_mutex.h
unique_lock.h
cxxabi_forced.h
error_constants.h
std::cv_status
cv_status
cv_status
Definition condition_variable:69
std::shared_ptr::make_shared
shared_ptr< _NonArray< _Tp > > make_shared(_Args &&... __args)
Create an object that is owned by a shared_ptr.
Definition bits/shared_ptr.h:1043
std::move
constexpr std::remove_reference< _Tp >::type && move(_Tp &&__t) noexcept
Convert a value to an rvalue.
Definition move.h:138
std::uncaught_exception
bool uncaught_exception() noexcept
std
ISO C++ entities toplevel namespace is std.
std::condition_variable
condition_variable
Definition condition_variable:73
std::chrono::duration
chrono::duration represents a distance between two points in time
Definition chrono.h:516
std::chrono::time_point
chrono::time_point represents a point in time as measured by a clock
Definition chrono.h:931
std::chrono::system_clock
System clock.
Definition chrono.h:1235
std::chrono::steady_clock
Monotonic clock.
Definition chrono.h:1277
__cxxabiv1::__forced_unwind
Thrown as part of forced unwinding.
Definition cxxabi_forced.h:51
std::shared_ptr
A smart pointer with reference-counted copy semantics.
Definition bits/shared_ptr.h:158
std::lock_guard
A simple scoped lock type.
Definition std_mutex.h:270
std::unique_lock
A movable scoped lock type.
Definition unique_lock.h:63
alloc_traits.h
shared_ptr.h