3 // Copyright (C) 2003-2019 Free Software Foundation, Inc.
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)
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.
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.
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/>.
25 /** @file include/mutex
26 * This is a Standard C++ Library header.
29 #ifndef _GLIBCXX_MUTEX
30 #define _GLIBCXX_MUTEX 1
32 #pragma GCC system_header
34 #if __cplusplus < 201103L
35 # include <bits/c++0x_warning.h>
41 #include <type_traits>
42 #include <system_error>
43 #include <bits/std_mutex.h>
44 #include <bits/unique_lock.h>
45 #if ! _GTHREAD_USE_MUTEX_TIMEDLOCK
46 # include <condition_variable>
49 #ifndef _GLIBCXX_HAVE_TLS
50 # include <bits/std_function.h>
53 namespace std _GLIBCXX_VISIBILITY(default)
55 _GLIBCXX_BEGIN_NAMESPACE_VERSION
62 #ifdef _GLIBCXX_HAS_GTHREADS
64 // Common base class for std::recursive_mutex and std::recursive_timed_mutex
65 class __recursive_mutex_base
68 typedef __gthread_recursive_mutex_t __native_type;
70 __recursive_mutex_base(const __recursive_mutex_base&) = delete;
71 __recursive_mutex_base& operator=(const __recursive_mutex_base&) = delete;
73 #ifdef __GTHREAD_RECURSIVE_MUTEX_INIT
74 __native_type _M_mutex = __GTHREAD_RECURSIVE_MUTEX_INIT;
76 __recursive_mutex_base() = default;
78 __native_type _M_mutex;
80 __recursive_mutex_base()
82 // XXX EAGAIN, ENOMEM, EPERM, EBUSY(may), EINVAL(may)
83 __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION(&_M_mutex);
86 ~__recursive_mutex_base()
87 { __gthread_recursive_mutex_destroy(&_M_mutex); }
91 /// The standard recursive mutex type.
92 class recursive_mutex : private __recursive_mutex_base
95 typedef __native_type* native_handle_type;
97 recursive_mutex() = default;
98 ~recursive_mutex() = default;
100 recursive_mutex(const recursive_mutex&) = delete;
101 recursive_mutex& operator=(const recursive_mutex&) = delete;
106 int __e = __gthread_recursive_mutex_lock(&_M_mutex);
108 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
110 __throw_system_error(__e);
116 // XXX EINVAL, EAGAIN, EBUSY
117 return !__gthread_recursive_mutex_trylock(&_M_mutex);
123 // XXX EINVAL, EAGAIN, EBUSY
124 __gthread_recursive_mutex_unlock(&_M_mutex);
128 native_handle() noexcept
129 { return &_M_mutex; }
132 #if _GTHREAD_USE_MUTEX_TIMEDLOCK
133 template<typename _Derived>
134 class __timed_mutex_impl
137 typedef chrono::high_resolution_clock __clock_t;
139 template<typename _Rep, typename _Period>
141 _M_try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
143 using chrono::steady_clock;
144 auto __rt = chrono::duration_cast<steady_clock::duration>(__rtime);
145 if (ratio_greater<steady_clock::period, _Period>())
147 return _M_try_lock_until(steady_clock::now() + __rt);
150 template<typename _Duration>
152 _M_try_lock_until(const chrono::time_point<__clock_t,
155 auto __s = chrono::time_point_cast<chrono::seconds>(__atime);
156 auto __ns = chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
158 __gthread_time_t __ts = {
159 static_cast<std::time_t>(__s.time_since_epoch().count()),
160 static_cast<long>(__ns.count())
163 return static_cast<_Derived*>(this)->_M_timedlock(__ts);
166 template<typename _Clock, typename _Duration>
168 _M_try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
170 auto __rtime = __atime - _Clock::now();
171 return _M_try_lock_until(__clock_t::now() + __rtime);
175 /// The standard timed mutex type.
177 : private __mutex_base, public __timed_mutex_impl<timed_mutex>
180 typedef __native_type* native_handle_type;
182 timed_mutex() = default;
183 ~timed_mutex() = default;
185 timed_mutex(const timed_mutex&) = delete;
186 timed_mutex& operator=(const timed_mutex&) = delete;
191 int __e = __gthread_mutex_lock(&_M_mutex);
193 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
195 __throw_system_error(__e);
201 // XXX EINVAL, EAGAIN, EBUSY
202 return !__gthread_mutex_trylock(&_M_mutex);
205 template <class _Rep, class _Period>
207 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
208 { return _M_try_lock_for(__rtime); }
210 template <class _Clock, class _Duration>
212 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
213 { return _M_try_lock_until(__atime); }
218 // XXX EINVAL, EAGAIN, EBUSY
219 __gthread_mutex_unlock(&_M_mutex);
223 native_handle() noexcept
224 { return &_M_mutex; }
227 friend class __timed_mutex_impl<timed_mutex>;
230 _M_timedlock(const __gthread_time_t& __ts)
231 { return !__gthread_mutex_timedlock(&_M_mutex, &__ts); }
234 /// recursive_timed_mutex
235 class recursive_timed_mutex
236 : private __recursive_mutex_base,
237 public __timed_mutex_impl<recursive_timed_mutex>
240 typedef __native_type* native_handle_type;
242 recursive_timed_mutex() = default;
243 ~recursive_timed_mutex() = default;
245 recursive_timed_mutex(const recursive_timed_mutex&) = delete;
246 recursive_timed_mutex& operator=(const recursive_timed_mutex&) = delete;
251 int __e = __gthread_recursive_mutex_lock(&_M_mutex);
253 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
255 __throw_system_error(__e);
261 // XXX EINVAL, EAGAIN, EBUSY
262 return !__gthread_recursive_mutex_trylock(&_M_mutex);
265 template <class _Rep, class _Period>
267 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
268 { return _M_try_lock_for(__rtime); }
270 template <class _Clock, class _Duration>
272 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
273 { return _M_try_lock_until(__atime); }
278 // XXX EINVAL, EAGAIN, EBUSY
279 __gthread_recursive_mutex_unlock(&_M_mutex);
283 native_handle() noexcept
284 { return &_M_mutex; }
287 friend class __timed_mutex_impl<recursive_timed_mutex>;
290 _M_timedlock(const __gthread_time_t& __ts)
291 { return !__gthread_recursive_mutex_timedlock(&_M_mutex, &__ts); }
294 #else // !_GTHREAD_USE_MUTEX_TIMEDLOCK
300 condition_variable _M_cv;
301 bool _M_locked = false;
305 timed_mutex() = default;
306 ~timed_mutex() { __glibcxx_assert( !_M_locked ); }
308 timed_mutex(const timed_mutex&) = delete;
309 timed_mutex& operator=(const timed_mutex&) = delete;
314 unique_lock<mutex> __lk(_M_mut);
315 _M_cv.wait(__lk, [&]{ return !_M_locked; });
322 lock_guard<mutex> __lk(_M_mut);
329 template<typename _Rep, typename _Period>
331 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
333 unique_lock<mutex> __lk(_M_mut);
334 if (!_M_cv.wait_for(__lk, __rtime, [&]{ return !_M_locked; }))
340 template<typename _Clock, typename _Duration>
342 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
344 unique_lock<mutex> __lk(_M_mut);
345 if (!_M_cv.wait_until(__lk, __atime, [&]{ return !_M_locked; }))
354 lock_guard<mutex> __lk(_M_mut);
355 __glibcxx_assert( _M_locked );
361 /// recursive_timed_mutex
362 class recursive_timed_mutex
365 condition_variable _M_cv;
367 unsigned _M_count = 0;
369 // Predicate type that tests whether the current thread can lock a mutex.
372 // Returns true if the mutex is unlocked or is locked by _M_caller.
374 operator()() const noexcept
375 { return _M_mx->_M_count == 0 || _M_mx->_M_owner == _M_caller; }
377 const recursive_timed_mutex* _M_mx;
378 thread::id _M_caller;
383 recursive_timed_mutex() = default;
384 ~recursive_timed_mutex() { __glibcxx_assert( _M_count == 0 ); }
386 recursive_timed_mutex(const recursive_timed_mutex&) = delete;
387 recursive_timed_mutex& operator=(const recursive_timed_mutex&) = delete;
392 auto __id = this_thread::get_id();
393 _Can_lock __can_lock{this, __id};
394 unique_lock<mutex> __lk(_M_mut);
395 _M_cv.wait(__lk, __can_lock);
397 __throw_system_error(EAGAIN); // [thread.timedmutex.recursive]/3
405 auto __id = this_thread::get_id();
406 _Can_lock __can_lock{this, __id};
407 lock_guard<mutex> __lk(_M_mut);
417 template<typename _Rep, typename _Period>
419 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
421 auto __id = this_thread::get_id();
422 _Can_lock __can_lock{this, __id};
423 unique_lock<mutex> __lk(_M_mut);
424 if (!_M_cv.wait_for(__lk, __rtime, __can_lock))
433 template<typename _Clock, typename _Duration>
435 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
437 auto __id = this_thread::get_id();
438 _Can_lock __can_lock{this, __id};
439 unique_lock<mutex> __lk(_M_mut);
440 if (!_M_cv.wait_until(__lk, __atime, __can_lock))
452 lock_guard<mutex> __lk(_M_mut);
453 __glibcxx_assert( _M_owner == this_thread::get_id() );
454 __glibcxx_assert( _M_count > 0 );
464 #endif // _GLIBCXX_HAS_GTHREADS
466 template<typename _Lock>
467 inline unique_lock<_Lock>
468 __try_to_lock(_Lock& __l)
469 { return unique_lock<_Lock>{__l, try_to_lock}; }
471 template<int _Idx, bool _Continue = true>
472 struct __try_lock_impl
474 template<typename... _Lock>
476 __do_try_lock(tuple<_Lock&...>& __locks, int& __idx)
479 auto __lock = std::__try_to_lock(std::get<_Idx>(__locks));
480 if (__lock.owns_lock())
482 constexpr bool __cont = _Idx + 2 < sizeof...(_Lock);
483 using __try_locker = __try_lock_impl<_Idx + 1, __cont>;
484 __try_locker::__do_try_lock(__locks, __idx);
492 struct __try_lock_impl<_Idx, false>
494 template<typename... _Lock>
496 __do_try_lock(tuple<_Lock&...>& __locks, int& __idx)
499 auto __lock = std::__try_to_lock(std::get<_Idx>(__locks));
500 if (__lock.owns_lock())
508 /** @brief Generic try_lock.
509 * @param __l1 Meets Lockable requirements (try_lock() may throw).
510 * @param __l2 Meets Lockable requirements (try_lock() may throw).
511 * @param __l3 Meets Lockable requirements (try_lock() may throw).
512 * @return Returns -1 if all try_lock() calls return true. Otherwise returns
513 * a 0-based index corresponding to the argument that returned false.
514 * @post Either all arguments are locked, or none will be.
516 * Sequentially calls try_lock() on each argument.
518 template<typename _Lock1, typename _Lock2, typename... _Lock3>
520 try_lock(_Lock1& __l1, _Lock2& __l2, _Lock3&... __l3)
523 auto __locks = std::tie(__l1, __l2, __l3...);
524 __try_lock_impl<0>::__do_try_lock(__locks, __idx);
528 /** @brief Generic lock.
529 * @param __l1 Meets Lockable requirements (try_lock() may throw).
530 * @param __l2 Meets Lockable requirements (try_lock() may throw).
531 * @param __l3 Meets Lockable requirements (try_lock() may throw).
532 * @throw An exception thrown by an argument's lock() or try_lock() member.
533 * @post All arguments are locked.
535 * All arguments are locked via a sequence of calls to lock(), try_lock()
536 * and unlock(). If the call exits via an exception any locks that were
537 * obtained will be released.
539 template<typename _L1, typename _L2, typename... _L3>
541 lock(_L1& __l1, _L2& __l2, _L3&... __l3)
545 using __try_locker = __try_lock_impl<0, sizeof...(_L3) != 0>;
546 unique_lock<_L1> __first(__l1);
548 auto __locks = std::tie(__l2, __l3...);
549 __try_locker::__do_try_lock(__locks, __idx);
558 #if __cplusplus >= 201703L
559 #define __cpp_lib_scoped_lock 201703
560 /** @brief A scoped lock type for multiple lockable objects.
562 * A scoped_lock controls mutex ownership within a scope, releasing
563 * ownership in the destructor.
565 template<typename... _MutexTypes>
569 explicit scoped_lock(_MutexTypes&... __m) : _M_devices(std::tie(__m...))
570 { std::lock(__m...); }
572 explicit scoped_lock(adopt_lock_t, _MutexTypes&... __m) noexcept
573 : _M_devices(std::tie(__m...))
574 { } // calling thread owns mutex
578 std::apply([](_MutexTypes&... __m) {
579 char __i[] __attribute__((__unused__)) = { (__m.unlock(), 0)... };
583 scoped_lock(const scoped_lock&) = delete;
584 scoped_lock& operator=(const scoped_lock&) = delete;
587 tuple<_MutexTypes&...> _M_devices;
594 explicit scoped_lock() = default;
595 explicit scoped_lock(adopt_lock_t) noexcept { }
596 ~scoped_lock() = default;
598 scoped_lock(const scoped_lock&) = delete;
599 scoped_lock& operator=(const scoped_lock&) = delete;
602 template<typename _Mutex>
603 class scoped_lock<_Mutex>
606 using mutex_type = _Mutex;
608 explicit scoped_lock(mutex_type& __m) : _M_device(__m)
609 { _M_device.lock(); }
611 explicit scoped_lock(adopt_lock_t, mutex_type& __m) noexcept
613 { } // calling thread owns mutex
616 { _M_device.unlock(); }
618 scoped_lock(const scoped_lock&) = delete;
619 scoped_lock& operator=(const scoped_lock&) = delete;
622 mutex_type& _M_device;
626 #ifdef _GLIBCXX_HAS_GTHREADS
631 typedef __gthread_once_t __native_type;
632 __native_type _M_once = __GTHREAD_ONCE_INIT;
636 constexpr once_flag() noexcept = default;
638 /// Deleted copy constructor
639 once_flag(const once_flag&) = delete;
640 /// Deleted assignment operator
641 once_flag& operator=(const once_flag&) = delete;
643 template<typename _Callable, typename... _Args>
645 call_once(once_flag& __once, _Callable&& __f, _Args&&... __args);
648 #ifdef _GLIBCXX_HAVE_TLS
649 extern __thread void* __once_callable;
650 extern __thread void (*__once_call)();
652 extern function<void()> __once_functor;
655 __set_once_functor_lock_ptr(unique_lock<mutex>*);
661 extern "C" void __once_proxy(void);
664 template<typename _Callable, typename... _Args>
666 call_once(once_flag& __once, _Callable&& __f, _Args&&... __args)
668 // _GLIBCXX_RESOLVE_LIB_DEFECTS
669 // 2442. call_once() shouldn't DECAY_COPY()
670 auto __callable = [&] {
671 std::__invoke(std::forward<_Callable>(__f),
672 std::forward<_Args>(__args)...);
674 #ifdef _GLIBCXX_HAVE_TLS
675 __once_callable = std::__addressof(__callable);
676 __once_call = []{ (*(decltype(__callable)*)__once_callable)(); };
678 unique_lock<mutex> __functor_lock(__get_once_mutex());
679 __once_functor = __callable;
680 __set_once_functor_lock_ptr(&__functor_lock);
683 int __e = __gthread_once(&__once._M_once, &__once_proxy);
685 #ifndef _GLIBCXX_HAVE_TLS
687 __set_once_functor_lock_ptr(0);
690 #ifdef __clang_analyzer__
691 // PR libstdc++/82481
692 __once_callable = nullptr;
693 __once_call = nullptr;
697 __throw_system_error(__e);
699 #endif // _GLIBCXX_HAS_GTHREADS
702 _GLIBCXX_END_NAMESPACE_VERSION
707 #endif // _GLIBCXX_MUTEX