libstdc++
condition_variable
Go to the documentation of this file.
1// <condition_variable> -*- C++ -*-
2
3// Copyright (C) 2008-2020 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#pragma GCC system_header
33
34#if __cplusplus < 201103L
35# include <bits/c++0x_warning.h>
36#else
37
38#include <chrono>
39
40#include <bits/std_mutex.h>
41#include <bits/unique_lock.h>
42#include <ext/concurrence.h>
43#include <bits/alloc_traits.h>
44#include <bits/allocator.h>
45#include <bits/unique_ptr.h>
46#include <bits/shared_ptr.h>
47#include <bits/cxxabi_forced.h>
48
49#if __cplusplus > 201703L
50#define __cpp_lib_jthread 201907L
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
73 {
76#ifdef _GLIBCXX_USE_PTHREAD_COND_CLOCKWAIT
77 using __clock_t = steady_clock;
78#else
79 using __clock_t = system_clock;
80#endif
81 typedef __gthread_cond_t __native_type;
82
83#ifdef __GTHREAD_COND_INIT
84 __native_type _M_cond = __GTHREAD_COND_INIT;
85#else
86 __native_type _M_cond;
87#endif
88
89 public:
90 typedef __native_type* native_handle_type;
91
92 condition_variable() noexcept;
93 ~condition_variable() noexcept;
94
96 condition_variable& operator=(const condition_variable&) = delete;
97
98 void
99 notify_one() noexcept;
100
101 void
102 notify_all() noexcept;
103
104 void
105 wait(unique_lock<mutex>& __lock) noexcept;
106
107 template<typename _Predicate>
108 void
109 wait(unique_lock<mutex>& __lock, _Predicate __p)
110 {
111 while (!__p())
112 wait(__lock);
113 }
114
115#ifdef _GLIBCXX_USE_PTHREAD_COND_CLOCKWAIT
116 template<typename _Duration>
118 wait_until(unique_lock<mutex>& __lock,
120 { return __wait_until_impl(__lock, __atime); }
121#endif
122
123 template<typename _Duration>
125 wait_until(unique_lock<mutex>& __lock,
127 { return __wait_until_impl(__lock, __atime); }
128
129 template<typename _Clock, typename _Duration>
131 wait_until(unique_lock<mutex>& __lock,
133 {
134#if __cplusplus > 201703L
135 static_assert(chrono::is_clock_v<_Clock>);
136#endif
137 const typename _Clock::time_point __c_entry = _Clock::now();
138 const __clock_t::time_point __s_entry = __clock_t::now();
139 const auto __delta = __atime - __c_entry;
140 const auto __s_atime = __s_entry + __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,
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>
166 wait_for(unique_lock<mutex>& __lock,
167 const chrono::duration<_Rep, _Period>& __rtime)
168 {
169 using __dur = typename steady_clock::duration;
170 auto __reltime = chrono::duration_cast<__dur>(__rtime);
171 if (__reltime < __rtime)
172 ++__reltime;
173 return wait_until(__lock, steady_clock::now() + __reltime);
174 }
175
176 template<typename _Rep, typename _Period, typename _Predicate>
177 bool
178 wait_for(unique_lock<mutex>& __lock,
179 const chrono::duration<_Rep, _Period>& __rtime,
180 _Predicate __p)
181 {
182 using __dur = typename steady_clock::duration;
183 auto __reltime = chrono::duration_cast<__dur>(__rtime);
184 if (__reltime < __rtime)
185 ++__reltime;
186 return wait_until(__lock, steady_clock::now() + __reltime,
187 std::move(__p));
188 }
189
190 native_handle_type
191 native_handle()
192 { return &_M_cond; }
193
194 private:
195#ifdef _GLIBCXX_USE_PTHREAD_COND_CLOCKWAIT
196 template<typename _Dur>
198 __wait_until_impl(unique_lock<mutex>& __lock,
200 {
201 auto __s = chrono::time_point_cast<chrono::seconds>(__atime);
202 auto __ns = chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
203
204 __gthread_time_t __ts =
205 {
206 static_cast<std::time_t>(__s.time_since_epoch().count()),
207 static_cast<long>(__ns.count())
208 };
209
210 pthread_cond_clockwait(&_M_cond, __lock.mutex()->native_handle(),
211 CLOCK_MONOTONIC,
212 &__ts);
213
214 return (steady_clock::now() < __atime
215 ? cv_status::no_timeout : cv_status::timeout);
216 }
217#endif
218
219 template<typename _Dur>
221 __wait_until_impl(unique_lock<mutex>& __lock,
223 {
224 auto __s = chrono::time_point_cast<chrono::seconds>(__atime);
225 auto __ns = chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
226
227 __gthread_time_t __ts =
228 {
229 static_cast<std::time_t>(__s.time_since_epoch().count()),
230 static_cast<long>(__ns.count())
231 };
232
233 __gthread_cond_timedwait(&_M_cond, __lock.mutex()->native_handle(),
234 &__ts);
235
236 return (system_clock::now() < __atime
237 ? cv_status::no_timeout : cv_status::timeout);
238 }
239 };
240
241 void
242 notify_all_at_thread_exit(condition_variable&, unique_lock<mutex>);
243
244 struct __at_thread_exit_elt
245 {
246 __at_thread_exit_elt* _M_next;
247 void (*_M_cb)(void*);
248 };
249
250 inline namespace _V2 {
251
252 /// condition_variable_any
253 // Like above, but mutex is not required to have try_lock.
255 {
256#ifdef _GLIBCXX_USE_PTHREAD_COND_CLOCKWAIT
258#else
260#endif
261 condition_variable _M_cond;
262 shared_ptr<mutex> _M_mutex;
263
264 // scoped unlock - unlocks in ctor, re-locks in dtor
265 template<typename _Lock>
266 struct _Unlock
267 {
268 explicit _Unlock(_Lock& __lk) : _M_lock(__lk) { __lk.unlock(); }
269
270 ~_Unlock() noexcept(false)
271 {
272 if (uncaught_exception())
273 {
274 __try
275 { _M_lock.lock(); }
276 __catch(const __cxxabiv1::__forced_unwind&)
277 { __throw_exception_again; }
278 __catch(...)
279 { }
280 }
281 else
282 _M_lock.lock();
283 }
284
285 _Unlock(const _Unlock&) = delete;
286 _Unlock& operator=(const _Unlock&) = delete;
287
288 _Lock& _M_lock;
289 };
290
291 public:
292 condition_variable_any() : _M_mutex(std::make_shared<mutex>()) { }
293 ~condition_variable_any() = default;
294
296 condition_variable_any& operator=(const condition_variable_any&) = delete;
297
298 void
299 notify_one() noexcept
300 {
301 lock_guard<mutex> __lock(*_M_mutex);
302 _M_cond.notify_one();
303 }
304
305 void
306 notify_all() noexcept
307 {
308 lock_guard<mutex> __lock(*_M_mutex);
309 _M_cond.notify_all();
310 }
311
312 template<typename _Lock>
313 void
314 wait(_Lock& __lock)
315 {
316 shared_ptr<mutex> __mutex = _M_mutex;
317 unique_lock<mutex> __my_lock(*__mutex);
318 _Unlock<_Lock> __unlock(__lock);
319 // *__mutex must be unlocked before re-locking __lock so move
320 // ownership of *__mutex lock to an object with shorter lifetime.
321 unique_lock<mutex> __my_lock2(std::move(__my_lock));
322 _M_cond.wait(__my_lock2);
323 }
324
325
326 template<typename _Lock, typename _Predicate>
327 void
328 wait(_Lock& __lock, _Predicate __p)
329 {
330 while (!__p())
331 wait(__lock);
332 }
333
334 template<typename _Lock, typename _Clock, typename _Duration>
336 wait_until(_Lock& __lock,
338 {
339 shared_ptr<mutex> __mutex = _M_mutex;
340 unique_lock<mutex> __my_lock(*__mutex);
341 _Unlock<_Lock> __unlock(__lock);
342 // *__mutex must be unlocked before re-locking __lock so move
343 // ownership of *__mutex lock to an object with shorter lifetime.
344 unique_lock<mutex> __my_lock2(std::move(__my_lock));
345 return _M_cond.wait_until(__my_lock2, __atime);
346 }
347
348 template<typename _Lock, typename _Clock,
349 typename _Duration, typename _Predicate>
350 bool
351 wait_until(_Lock& __lock,
353 _Predicate __p)
354 {
355 while (!__p())
356 if (wait_until(__lock, __atime) == cv_status::timeout)
357 return __p();
358 return true;
359 }
360
361 template<typename _Lock, typename _Rep, typename _Period>
363 wait_for(_Lock& __lock, const chrono::duration<_Rep, _Period>& __rtime)
364 { return wait_until(__lock, __clock_t::now() + __rtime); }
365
366 template<typename _Lock, typename _Rep,
367 typename _Period, typename _Predicate>
368 bool
369 wait_for(_Lock& __lock,
370 const chrono::duration<_Rep, _Period>& __rtime, _Predicate __p)
371 { return wait_until(__lock, __clock_t::now() + __rtime, std::move(__p)); }
372
373#ifdef __cpp_lib_jthread
374 template <class _Lock, class _Predicate>
375 bool wait(_Lock& __lock,
376 stop_token __stoken,
377 _Predicate __p)
378 {
379 if (__stoken.stop_requested())
380 {
381 return __p();
382 }
383
384 std::stop_callback __cb(__stoken, [this] { notify_all(); });
385 shared_ptr<mutex> __mutex = _M_mutex;
386 while (!__p())
387 {
388 unique_lock<mutex> __my_lock(*__mutex);
389 if (__stoken.stop_requested())
390 {
391 return false;
392 }
393 // *__mutex must be unlocked before re-locking __lock so move
394 // ownership of *__mutex lock to an object with shorter lifetime.
395 _Unlock<_Lock> __unlock(__lock);
396 unique_lock<mutex> __my_lock2(std::move(__my_lock));
397 _M_cond.wait(__my_lock2);
398 }
399 return true;
400 }
401
402 template <class _Lock, class _Clock, class _Duration, class _Predicate>
403 bool wait_until(_Lock& __lock,
404 stop_token __stoken,
406 _Predicate __p)
407 {
408 if (__stoken.stop_requested())
409 {
410 return __p();
411 }
412
413 std::stop_callback __cb(__stoken, [this] { notify_all(); });
414 shared_ptr<mutex> __mutex = _M_mutex;
415 while (!__p())
416 {
417 bool __stop;
418 {
419 unique_lock<mutex> __my_lock(*__mutex);
420 if (__stoken.stop_requested())
421 {
422 return false;
423 }
424 _Unlock<_Lock> __u(__lock);
425 unique_lock<mutex> __my_lock2(std::move(__my_lock));
426 const auto __status = _M_cond.wait_until(__my_lock2, __abs_time);
427 __stop = (__status == std::cv_status::timeout) || __stoken.stop_requested();
428 }
429 if (__stop)
430 {
431 return __p();
432 }
433 }
434 return true;
435 }
436
437 template <class _Lock, class _Rep, class _Period, class _Predicate>
438 bool wait_for(_Lock& __lock,
439 stop_token __stoken,
440 const chrono::duration<_Rep, _Period>& __rel_time,
441 _Predicate __p)
442 {
443 auto __abst = std::chrono::steady_clock::now() + __rel_time;
444 return wait_until(__lock,
445 std::move(__stoken),
446 __abst,
447 std::move(__p));
448 }
449#endif
450 };
451
452 } // end inline namespace
453
454 // @} group condition_variables
455_GLIBCXX_END_NAMESPACE_VERSION
456} // namespace
457
458#endif // _GLIBCXX_HAS_GTHREADS
459#endif // C++11
460#endif // _GLIBCXX_CONDITION_VARIABLE
cv_status
cv_status
constexpr std::remove_reference< _Tp >::type && move(_Tp &&__t) noexcept
Convert a value to an rvalue.
Definition: move.h:101
bool uncaught_exception() noexcept
ISO C++ entities toplevel namespace is std.
time_point
Definition: chrono:748
System clock.
Definition: chrono:965
Monotonic clock.
Definition: chrono:1005
condition_variable
Thrown as part of forced unwinding.
Definition: cxxabi_forced.h:49
A smart pointer with reference-counted copy semantics.
A simple scoped lock type.
Definition: std_mutex.h:154
A movable scoped lock type.
Definition: unique_lock.h:57