3 // Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2013
4 // Free Software Foundation, Inc.
6 // This file is part of the GNU ISO C++ Library. This library is free
7 // software; you can redistribute it and/or modify it under the
8 // terms of the GNU General Public License as published by the
9 // Free Software Foundation; either version 3, or (at your option)
12 // This library is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 // GNU General Public License for more details.
17 // Under Section 7 of GPL version 3, you are granted additional
18 // permissions described in the GCC Runtime Library Exception, version
19 // 3.1, as published by the Free Software Foundation.
21 // You should have received a copy of the GNU General Public License and
22 // a copy of the GCC Runtime Library Exception along with this program;
23 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
24 // <http://www.gnu.org/licenses/>.
26 /** @file include/mutex
27 * This is a Standard C++ Library header.
30 #ifndef _GLIBCXX_MUTEX
31 #define _GLIBCXX_MUTEX 1
33 #pragma GCC system_header
35 #ifndef __GXX_EXPERIMENTAL_CXX0X__
36 # include <bits/c++0x_warning.h>
42 #include <type_traits>
44 #include <system_error>
45 #include <bits/functexcept.h>
46 #include <bits/gthr.h>
47 #include <bits/move.h> // for std::swap
49 #ifdef _GLIBCXX_USE_C99_STDINT_TR1
51 namespace std _GLIBCXX_VISIBILITY(default)
53 _GLIBCXX_BEGIN_NAMESPACE_VERSION
55 #ifdef _GLIBCXX_HAS_GTHREADS
56 // Common base class for std::mutex and std::timed_mutex
60 typedef __gthread_mutex_t __native_type;
62 #ifdef __GTHREAD_MUTEX_INIT
63 __native_type _M_mutex = __GTHREAD_MUTEX_INIT;
65 constexpr __mutex_base() noexcept = default;
67 __native_type _M_mutex;
69 __mutex_base() noexcept
71 // XXX EAGAIN, ENOMEM, EPERM, EBUSY(may), EINVAL(may)
72 __GTHREAD_MUTEX_INIT_FUNCTION(&_M_mutex);
75 ~__mutex_base() noexcept { __gthread_mutex_destroy(&_M_mutex); }
78 __mutex_base(const __mutex_base&) = delete;
79 __mutex_base& operator=(const __mutex_base&) = delete;
82 // Common base class for std::recursive_mutex and std::timed_recursive_mutex
83 class __recursive_mutex_base
86 typedef __gthread_recursive_mutex_t __native_type;
88 __recursive_mutex_base(const __recursive_mutex_base&) = delete;
89 __recursive_mutex_base& operator=(const __recursive_mutex_base&) = delete;
91 #ifdef __GTHREAD_RECURSIVE_MUTEX_INIT
92 __native_type _M_mutex = __GTHREAD_RECURSIVE_MUTEX_INIT;
94 __recursive_mutex_base() = default;
96 __native_type _M_mutex;
98 __recursive_mutex_base()
100 // XXX EAGAIN, ENOMEM, EPERM, EBUSY(may), EINVAL(may)
101 __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION(&_M_mutex);
104 ~__recursive_mutex_base()
105 { _S_destroy(&_M_mutex); }
108 // FIXME: gthreads doesn't define __gthread_recursive_mutex_destroy
109 // so we need to obtain a __gthread_mutex_t to destroy
111 // matches when there's only one mutex type
112 template<typename _Rm>
114 typename enable_if<is_same<_Rm, __gthread_mutex_t>::value, void>::type
115 _S_destroy(_Rm* __mx)
116 { __gthread_mutex_destroy(__mx); }
118 // matches a recursive mutex with a member 'actual'
119 template<typename _Rm>
120 static typename enable_if<(bool)sizeof(&_Rm::actual), void>::type
121 _S_destroy(_Rm* __mx)
122 { __gthread_mutex_destroy(&__mx->actual); }
124 // matches a gthr-win32.h recursive mutex
125 template<typename _Rm>
126 static typename enable_if<(bool)sizeof(&_Rm::sema), void>::type
127 _S_destroy(_Rm* __mx)
129 __gthread_mutex_t __tmp;
130 _S_destroy_win32(&__tmp, __mx);
133 template<typename _Mx, typename _Rm>
135 _S_destroy_win32(_Mx* __mx, _Rm const* __rmx)
137 __mx->counter = __rmx->counter;
138 __mx->sema = __rmx->sema;
139 __gthread_mutex_destroy(__mx);
145 * @defgroup mutexes Mutexes
146 * @ingroup concurrency
148 * Classes for mutex support.
153 class mutex : private __mutex_base
156 typedef __native_type* native_handle_type;
158 #ifdef __GTHREAD_MUTEX_INIT
161 mutex() noexcept = default;
164 mutex(const mutex&) = delete;
165 mutex& operator=(const mutex&) = delete;
170 int __e = __gthread_mutex_lock(&_M_mutex);
172 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
174 __throw_system_error(__e);
180 // XXX EINVAL, EAGAIN, EBUSY
181 return !__gthread_mutex_trylock(&_M_mutex);
187 // XXX EINVAL, EAGAIN, EPERM
188 __gthread_mutex_unlock(&_M_mutex);
193 { return &_M_mutex; }
197 class recursive_mutex : private __recursive_mutex_base
200 typedef __native_type* native_handle_type;
202 recursive_mutex() = default;
203 ~recursive_mutex() = default;
205 recursive_mutex(const recursive_mutex&) = delete;
206 recursive_mutex& operator=(const recursive_mutex&) = delete;
211 int __e = __gthread_recursive_mutex_lock(&_M_mutex);
213 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
215 __throw_system_error(__e);
221 // XXX EINVAL, EAGAIN, EBUSY
222 return !__gthread_recursive_mutex_trylock(&_M_mutex);
228 // XXX EINVAL, EAGAIN, EBUSY
229 __gthread_recursive_mutex_unlock(&_M_mutex);
234 { return &_M_mutex; }
237 #if _GTHREAD_USE_MUTEX_TIMEDLOCK
239 class timed_mutex : private __mutex_base
241 #ifdef _GLIBCXX_USE_CLOCK_MONOTONIC
242 typedef chrono::steady_clock __clock_t;
244 typedef chrono::high_resolution_clock __clock_t;
248 typedef __native_type* native_handle_type;
250 timed_mutex() = default;
251 ~timed_mutex() = default;
253 timed_mutex(const timed_mutex&) = delete;
254 timed_mutex& operator=(const timed_mutex&) = delete;
259 int __e = __gthread_mutex_lock(&_M_mutex);
261 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
263 __throw_system_error(__e);
269 // XXX EINVAL, EAGAIN, EBUSY
270 return !__gthread_mutex_trylock(&_M_mutex);
273 template <class _Rep, class _Period>
275 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
276 { return __try_lock_for_impl(__rtime); }
278 template <class _Clock, class _Duration>
280 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
282 chrono::time_point<_Clock, chrono::seconds> __s =
283 chrono::time_point_cast<chrono::seconds>(__atime);
285 chrono::nanoseconds __ns =
286 chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
288 __gthread_time_t __ts = {
289 static_cast<std::time_t>(__s.time_since_epoch().count()),
290 static_cast<long>(__ns.count())
293 return !__gthread_mutex_timedlock(&_M_mutex, &__ts);
299 // XXX EINVAL, EAGAIN, EBUSY
300 __gthread_mutex_unlock(&_M_mutex);
305 { return &_M_mutex; }
308 template<typename _Rep, typename _Period>
310 ratio_less_equal<__clock_t::period, _Period>::value, bool>::type
311 __try_lock_for_impl(const chrono::duration<_Rep, _Period>& __rtime)
313 __clock_t::time_point __atime = __clock_t::now()
314 + chrono::duration_cast<__clock_t::duration>(__rtime);
316 return try_lock_until(__atime);
319 template <typename _Rep, typename _Period>
321 !ratio_less_equal<__clock_t::period, _Period>::value, bool>::type
322 __try_lock_for_impl(const chrono::duration<_Rep, _Period>& __rtime)
324 __clock_t::time_point __atime = __clock_t::now()
325 + ++chrono::duration_cast<__clock_t::duration>(__rtime);
327 return try_lock_until(__atime);
331 /// recursive_timed_mutex
332 class recursive_timed_mutex : private __recursive_mutex_base
334 #ifdef _GLIBCXX_USE_CLOCK_MONOTONIC
335 typedef chrono::steady_clock __clock_t;
337 typedef chrono::high_resolution_clock __clock_t;
341 typedef __native_type* native_handle_type;
343 recursive_timed_mutex() = default;
344 ~recursive_timed_mutex() = default;
346 recursive_timed_mutex(const recursive_timed_mutex&) = delete;
347 recursive_timed_mutex& operator=(const recursive_timed_mutex&) = delete;
352 int __e = __gthread_recursive_mutex_lock(&_M_mutex);
354 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
356 __throw_system_error(__e);
362 // XXX EINVAL, EAGAIN, EBUSY
363 return !__gthread_recursive_mutex_trylock(&_M_mutex);
366 template <class _Rep, class _Period>
368 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
369 { return __try_lock_for_impl(__rtime); }
371 template <class _Clock, class _Duration>
373 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
375 chrono::time_point<_Clock, chrono::seconds> __s =
376 chrono::time_point_cast<chrono::seconds>(__atime);
378 chrono::nanoseconds __ns =
379 chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
381 __gthread_time_t __ts = {
382 static_cast<std::time_t>(__s.time_since_epoch().count()),
383 static_cast<long>(__ns.count())
386 return !__gthread_recursive_mutex_timedlock(&_M_mutex, &__ts);
392 // XXX EINVAL, EAGAIN, EBUSY
393 __gthread_recursive_mutex_unlock(&_M_mutex);
398 { return &_M_mutex; }
401 template<typename _Rep, typename _Period>
403 ratio_less_equal<__clock_t::period, _Period>::value, bool>::type
404 __try_lock_for_impl(const chrono::duration<_Rep, _Period>& __rtime)
406 __clock_t::time_point __atime = __clock_t::now()
407 + chrono::duration_cast<__clock_t::duration>(__rtime);
409 return try_lock_until(__atime);
412 template <typename _Rep, typename _Period>
414 !ratio_less_equal<__clock_t::period, _Period>::value, bool>::type
415 __try_lock_for_impl(const chrono::duration<_Rep, _Period>& __rtime)
417 __clock_t::time_point __atime = __clock_t::now()
418 + ++chrono::duration_cast<__clock_t::duration>(__rtime);
420 return try_lock_until(__atime);
424 #endif // _GLIBCXX_HAS_GTHREADS
426 /// Do not acquire ownership of the mutex.
427 struct defer_lock_t { };
429 /// Try to acquire ownership of the mutex without blocking.
430 struct try_to_lock_t { };
432 /// Assume the calling thread has already obtained mutex ownership
434 struct adopt_lock_t { };
436 constexpr defer_lock_t defer_lock { };
437 constexpr try_to_lock_t try_to_lock { };
438 constexpr adopt_lock_t adopt_lock { };
440 /// @brief Scoped lock idiom.
441 // Acquire the mutex here with a constructor call, then release with
442 // the destructor call in accordance with RAII style.
443 template<typename _Mutex>
447 typedef _Mutex mutex_type;
449 explicit lock_guard(mutex_type& __m) : _M_device(__m)
450 { _M_device.lock(); }
452 lock_guard(mutex_type& __m, adopt_lock_t) : _M_device(__m)
453 { } // calling thread owns mutex
456 { _M_device.unlock(); }
458 lock_guard(const lock_guard&) = delete;
459 lock_guard& operator=(const lock_guard&) = delete;
462 mutex_type& _M_device;
466 template<typename _Mutex>
470 typedef _Mutex mutex_type;
472 unique_lock() noexcept
473 : _M_device(0), _M_owns(false)
476 explicit unique_lock(mutex_type& __m)
477 : _M_device(&__m), _M_owns(false)
483 unique_lock(mutex_type& __m, defer_lock_t) noexcept
484 : _M_device(&__m), _M_owns(false)
487 unique_lock(mutex_type& __m, try_to_lock_t)
488 : _M_device(&__m), _M_owns(_M_device->try_lock())
491 unique_lock(mutex_type& __m, adopt_lock_t)
492 : _M_device(&__m), _M_owns(true)
494 // XXX calling thread owns mutex
497 template<typename _Clock, typename _Duration>
498 unique_lock(mutex_type& __m,
499 const chrono::time_point<_Clock, _Duration>& __atime)
500 : _M_device(&__m), _M_owns(_M_device->try_lock_until(__atime))
503 template<typename _Rep, typename _Period>
504 unique_lock(mutex_type& __m,
505 const chrono::duration<_Rep, _Period>& __rtime)
506 : _M_device(&__m), _M_owns(_M_device->try_lock_for(__rtime))
515 unique_lock(const unique_lock&) = delete;
516 unique_lock& operator=(const unique_lock&) = delete;
518 unique_lock(unique_lock&& __u) noexcept
519 : _M_device(__u._M_device), _M_owns(__u._M_owns)
525 unique_lock& operator=(unique_lock&& __u) noexcept
530 unique_lock(std::move(__u)).swap(*this);
542 __throw_system_error(int(errc::operation_not_permitted));
544 __throw_system_error(int(errc::resource_deadlock_would_occur));
556 __throw_system_error(int(errc::operation_not_permitted));
558 __throw_system_error(int(errc::resource_deadlock_would_occur));
561 _M_owns = _M_device->try_lock();
566 template<typename _Clock, typename _Duration>
568 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
571 __throw_system_error(int(errc::operation_not_permitted));
573 __throw_system_error(int(errc::resource_deadlock_would_occur));
576 _M_owns = _M_device->try_lock_until(__atime);
581 template<typename _Rep, typename _Period>
583 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
586 __throw_system_error(int(errc::operation_not_permitted));
588 __throw_system_error(int(errc::resource_deadlock_would_occur));
591 _M_owns = _M_device->try_lock_for(__rtime);
600 __throw_system_error(int(errc::operation_not_permitted));
609 swap(unique_lock& __u) noexcept
611 std::swap(_M_device, __u._M_device);
612 std::swap(_M_owns, __u._M_owns);
618 mutex_type* __ret = _M_device;
625 owns_lock() const noexcept
628 explicit operator bool() const noexcept
629 { return owns_lock(); }
632 mutex() const noexcept
633 { return _M_device; }
636 mutex_type* _M_device;
637 bool _M_owns; // XXX use atomic_bool
640 /// Partial specialization for unique_lock objects.
641 template<typename _Mutex>
643 swap(unique_lock<_Mutex>& __x, unique_lock<_Mutex>& __y) noexcept
649 template<typename... _Lock>
651 __do_unlock(tuple<_Lock&...>& __locks)
653 std::get<_Idx>(__locks).unlock();
654 __unlock_impl<_Idx - 1>::__do_unlock(__locks);
659 struct __unlock_impl<-1>
661 template<typename... _Lock>
663 __do_unlock(tuple<_Lock&...>&)
667 template<typename _Lock>
669 __try_to_lock(_Lock& __l)
670 { return unique_lock<_Lock>(__l, try_to_lock); }
672 template<int _Idx, bool _Continue = true>
673 struct __try_lock_impl
675 template<typename... _Lock>
677 __do_try_lock(tuple<_Lock&...>& __locks, int& __idx)
680 auto __lock = __try_to_lock(std::get<_Idx>(__locks));
681 if (__lock.owns_lock())
683 __try_lock_impl<_Idx + 1, _Idx + 2 < sizeof...(_Lock)>::
684 __do_try_lock(__locks, __idx);
692 struct __try_lock_impl<_Idx, false>
694 template<typename... _Lock>
696 __do_try_lock(tuple<_Lock&...>& __locks, int& __idx)
699 auto __lock = __try_to_lock(std::get<_Idx>(__locks));
700 if (__lock.owns_lock())
708 /** @brief Generic try_lock.
709 * @param __l1 Meets Mutex requirements (try_lock() may throw).
710 * @param __l2 Meets Mutex requirements (try_lock() may throw).
711 * @param __l3 Meets Mutex requirements (try_lock() may throw).
712 * @return Returns -1 if all try_lock() calls return true. Otherwise returns
713 * a 0-based index corresponding to the argument that returned false.
714 * @post Either all arguments are locked, or none will be.
716 * Sequentially calls try_lock() on each argument.
718 template<typename _Lock1, typename _Lock2, typename... _Lock3>
720 try_lock(_Lock1& __l1, _Lock2& __l2, _Lock3&... __l3)
723 auto __locks = std::tie(__l1, __l2, __l3...);
725 { __try_lock_impl<0>::__do_try_lock(__locks, __idx); }
731 /** @brief Generic lock.
732 * @param __l1 Meets Mutex requirements (try_lock() may throw).
733 * @param __l2 Meets Mutex requirements (try_lock() may throw).
734 * @param __l3 Meets Mutex requirements (try_lock() may throw).
735 * @throw An exception thrown by an argument's lock() or try_lock() member.
736 * @post All arguments are locked.
738 * All arguments are locked via a sequence of calls to lock(), try_lock()
739 * and unlock(). If the call exits via an exception any locks that were
740 * obtained will be released.
742 template<typename _L1, typename _L2, typename ..._L3>
744 lock(_L1& __l1, _L2& __l2, _L3&... __l3)
748 unique_lock<_L1> __first(__l1);
750 auto __locks = std::tie(__l2, __l3...);
751 __try_lock_impl<0, sizeof...(_L3)>::__do_try_lock(__locks, __idx);
760 #ifdef _GLIBCXX_HAS_GTHREADS
765 typedef __gthread_once_t __native_type;
766 __native_type _M_once = __GTHREAD_ONCE_INIT;
770 constexpr once_flag() noexcept = default;
772 /// Deleted copy constructor
773 once_flag(const once_flag&) = delete;
774 /// Deleted assignment operator
775 once_flag& operator=(const once_flag&) = delete;
777 template<typename _Callable, typename... _Args>
779 call_once(once_flag& __once, _Callable&& __f, _Args&&... __args);
782 #ifdef _GLIBCXX_HAVE_TLS
783 extern __thread void* __once_callable;
784 extern __thread void (*__once_call)();
786 template<typename _Callable>
790 (*(_Callable*)__once_callable)();
793 extern function<void()> __once_functor;
796 __set_once_functor_lock_ptr(unique_lock<mutex>*);
802 extern "C" void __once_proxy(void);
805 template<typename _Callable, typename... _Args>
807 call_once(once_flag& __once, _Callable&& __f, _Args&&... __args)
809 #ifdef _GLIBCXX_HAVE_TLS
810 auto __bound_functor = std::__bind_simple(std::forward<_Callable>(__f),
811 std::forward<_Args>(__args)...);
812 __once_callable = &__bound_functor;
813 __once_call = &__once_call_impl<decltype(__bound_functor)>;
815 unique_lock<mutex> __functor_lock(__get_once_mutex());
816 auto __callable = std::__bind_simple(std::forward<_Callable>(__f),
817 std::forward<_Args>(__args)...);
818 __once_functor = [&]() { __callable(); };
819 __set_once_functor_lock_ptr(&__functor_lock);
822 int __e = __gthread_once(&(__once._M_once), &__once_proxy);
824 #ifndef _GLIBCXX_HAVE_TLS
826 __set_once_functor_lock_ptr(0);
830 __throw_system_error(__e);
832 #endif // _GLIBCXX_HAS_GTHREADS
835 _GLIBCXX_END_NAMESPACE_VERSION
838 #endif // _GLIBCXX_USE_C99_STDINT_TR1
840 #endif // __GXX_EXPERIMENTAL_CXX0X__
842 #endif // _GLIBCXX_MUTEX