3 // Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
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 #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1)
51 namespace std _GLIBCXX_VISIBILITY(default)
53 _GLIBCXX_BEGIN_NAMESPACE_VERSION
55 // Common base class for std::mutex and std::timed_mutex
59 typedef __gthread_mutex_t __native_type;
61 #ifdef __GTHREAD_MUTEX_INIT
62 __native_type _M_mutex = __GTHREAD_MUTEX_INIT;
64 constexpr __mutex_base() noexcept = default;
66 __native_type _M_mutex;
68 __mutex_base() noexcept
70 // XXX EAGAIN, ENOMEM, EPERM, EBUSY(may), EINVAL(may)
71 __GTHREAD_MUTEX_INIT_FUNCTION(&_M_mutex);
74 ~__mutex_base() noexcept { __gthread_mutex_destroy(&_M_mutex); }
77 __mutex_base(const __mutex_base&) = delete;
78 __mutex_base& operator=(const __mutex_base&) = delete;
81 // Common base class for std::recursive_mutex and std::timed_recursive_mutex
82 class __recursive_mutex_base
85 typedef __gthread_recursive_mutex_t __native_type;
87 __recursive_mutex_base(const __recursive_mutex_base&) = delete;
88 __recursive_mutex_base& operator=(const __recursive_mutex_base&) = delete;
90 #ifdef __GTHREAD_RECURSIVE_MUTEX_INIT
91 __native_type _M_mutex = __GTHREAD_RECURSIVE_MUTEX_INIT;
93 __recursive_mutex_base() = default;
95 __native_type _M_mutex;
97 __recursive_mutex_base()
99 // XXX EAGAIN, ENOMEM, EPERM, EBUSY(may), EINVAL(may)
100 __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION(&_M_mutex);
103 ~__recursive_mutex_base()
104 { _S_destroy(&_M_mutex); }
107 // FIXME: gthreads doesn't define __gthread_recursive_mutex_destroy
108 // so we need to obtain a __gthread_mutex_t to destroy
110 // matches when there's only one mutex type
111 template<typename _Rm>
113 typename enable_if<is_same<_Rm, __gthread_mutex_t>::value, void>::type
114 _S_destroy(_Rm* __mx)
115 { __gthread_mutex_destroy(__mx); }
117 // matches a recursive mutex with a member 'actual'
118 template<typename _Rm>
119 static typename enable_if<(bool)sizeof(&_Rm::actual), void>::type
120 _S_destroy(_Rm* __mx)
121 { __gthread_mutex_destroy(&__mx->actual); }
123 // matches a gthr-win32.h recursive mutex
124 template<typename _Rm>
125 static typename enable_if<(bool)sizeof(&_Rm::sema), void>::type
126 _S_destroy(_Rm* __mx)
128 __gthread_mutex_t __tmp;
129 _S_destroy_win32(&__tmp, __mx);
132 template<typename _Mx, typename _Rm>
134 _S_destroy_win32(_Mx* __mx, _Rm const* __rmx)
136 __mx->counter = __rmx->counter;
137 __mx->sema = __rmx->sema;
138 __gthread_mutex_destroy(__mx);
144 * @defgroup mutexes Mutexes
145 * @ingroup concurrency
147 * Classes for mutex support.
152 class mutex : private __mutex_base
155 typedef __native_type* native_handle_type;
157 #ifdef __GTHREAD_MUTEX_INIT
160 mutex() noexcept = default;
163 mutex(const mutex&) = delete;
164 mutex& operator=(const mutex&) = delete;
169 int __e = __gthread_mutex_lock(&_M_mutex);
171 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
173 __throw_system_error(__e);
179 // XXX EINVAL, EAGAIN, EBUSY
180 return !__gthread_mutex_trylock(&_M_mutex);
186 // XXX EINVAL, EAGAIN, EPERM
187 __gthread_mutex_unlock(&_M_mutex);
192 { return &_M_mutex; }
196 class recursive_mutex : private __recursive_mutex_base
199 typedef __native_type* native_handle_type;
201 recursive_mutex() = default;
202 ~recursive_mutex() = default;
204 recursive_mutex(const recursive_mutex&) = delete;
205 recursive_mutex& operator=(const recursive_mutex&) = delete;
210 int __e = __gthread_recursive_mutex_lock(&_M_mutex);
212 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
214 __throw_system_error(__e);
220 // XXX EINVAL, EAGAIN, EBUSY
221 return !__gthread_recursive_mutex_trylock(&_M_mutex);
227 // XXX EINVAL, EAGAIN, EBUSY
228 __gthread_recursive_mutex_unlock(&_M_mutex);
233 { return &_M_mutex; }
236 #if _GTHREAD_USE_MUTEX_TIMEDLOCK
238 class timed_mutex : private __mutex_base
240 #ifdef _GLIBCXX_USE_CLOCK_MONOTONIC
241 typedef chrono::steady_clock __clock_t;
243 typedef chrono::high_resolution_clock __clock_t;
247 typedef __native_type* native_handle_type;
249 timed_mutex() = default;
250 ~timed_mutex() = default;
252 timed_mutex(const timed_mutex&) = delete;
253 timed_mutex& operator=(const timed_mutex&) = delete;
258 int __e = __gthread_mutex_lock(&_M_mutex);
260 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
262 __throw_system_error(__e);
268 // XXX EINVAL, EAGAIN, EBUSY
269 return !__gthread_mutex_trylock(&_M_mutex);
272 template <class _Rep, class _Period>
274 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
275 { return __try_lock_for_impl(__rtime); }
277 template <class _Clock, class _Duration>
279 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
281 chrono::time_point<_Clock, chrono::seconds> __s =
282 chrono::time_point_cast<chrono::seconds>(__atime);
284 chrono::nanoseconds __ns =
285 chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
287 __gthread_time_t __ts = {
288 static_cast<std::time_t>(__s.time_since_epoch().count()),
289 static_cast<long>(__ns.count())
292 return !__gthread_mutex_timedlock(&_M_mutex, &__ts);
298 // XXX EINVAL, EAGAIN, EBUSY
299 __gthread_mutex_unlock(&_M_mutex);
304 { return &_M_mutex; }
307 template<typename _Rep, typename _Period>
309 ratio_less_equal<__clock_t::period, _Period>::value, bool>::type
310 __try_lock_for_impl(const chrono::duration<_Rep, _Period>& __rtime)
312 __clock_t::time_point __atime = __clock_t::now()
313 + chrono::duration_cast<__clock_t::duration>(__rtime);
315 return try_lock_until(__atime);
318 template <typename _Rep, typename _Period>
320 !ratio_less_equal<__clock_t::period, _Period>::value, bool>::type
321 __try_lock_for_impl(const chrono::duration<_Rep, _Period>& __rtime)
323 __clock_t::time_point __atime = __clock_t::now()
324 + ++chrono::duration_cast<__clock_t::duration>(__rtime);
326 return try_lock_until(__atime);
330 /// recursive_timed_mutex
331 class recursive_timed_mutex : private __recursive_mutex_base
333 #ifdef _GLIBCXX_USE_CLOCK_MONOTONIC
334 typedef chrono::steady_clock __clock_t;
336 typedef chrono::high_resolution_clock __clock_t;
340 typedef __native_type* native_handle_type;
342 recursive_timed_mutex() = default;
343 ~recursive_timed_mutex() = default;
345 recursive_timed_mutex(const recursive_timed_mutex&) = delete;
346 recursive_timed_mutex& operator=(const recursive_timed_mutex&) = delete;
351 int __e = __gthread_recursive_mutex_lock(&_M_mutex);
353 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
355 __throw_system_error(__e);
361 // XXX EINVAL, EAGAIN, EBUSY
362 return !__gthread_recursive_mutex_trylock(&_M_mutex);
365 template <class _Rep, class _Period>
367 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
368 { return __try_lock_for_impl(__rtime); }
370 template <class _Clock, class _Duration>
372 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
374 chrono::time_point<_Clock, chrono::seconds> __s =
375 chrono::time_point_cast<chrono::seconds>(__atime);
377 chrono::nanoseconds __ns =
378 chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
380 __gthread_time_t __ts = {
381 static_cast<std::time_t>(__s.time_since_epoch().count()),
382 static_cast<long>(__ns.count())
385 return !__gthread_recursive_mutex_timedlock(&_M_mutex, &__ts);
391 // XXX EINVAL, EAGAIN, EBUSY
392 __gthread_recursive_mutex_unlock(&_M_mutex);
397 { return &_M_mutex; }
400 template<typename _Rep, typename _Period>
402 ratio_less_equal<__clock_t::period, _Period>::value, bool>::type
403 __try_lock_for_impl(const chrono::duration<_Rep, _Period>& __rtime)
405 __clock_t::time_point __atime = __clock_t::now()
406 + chrono::duration_cast<__clock_t::duration>(__rtime);
408 return try_lock_until(__atime);
411 template <typename _Rep, typename _Period>
413 !ratio_less_equal<__clock_t::period, _Period>::value, bool>::type
414 __try_lock_for_impl(const chrono::duration<_Rep, _Period>& __rtime)
416 __clock_t::time_point __atime = __clock_t::now()
417 + ++chrono::duration_cast<__clock_t::duration>(__rtime);
419 return try_lock_until(__atime);
424 /// Do not acquire ownership of the mutex.
425 struct defer_lock_t { };
427 /// Try to acquire ownership of the mutex without blocking.
428 struct try_to_lock_t { };
430 /// Assume the calling thread has already obtained mutex ownership
432 struct adopt_lock_t { };
434 constexpr defer_lock_t defer_lock { };
435 constexpr try_to_lock_t try_to_lock { };
436 constexpr adopt_lock_t adopt_lock { };
438 /// @brief Scoped lock idiom.
439 // Acquire the mutex here with a constructor call, then release with
440 // the destructor call in accordance with RAII style.
441 template<typename _Mutex>
445 typedef _Mutex mutex_type;
447 explicit lock_guard(mutex_type& __m) : _M_device(__m)
448 { _M_device.lock(); }
450 lock_guard(mutex_type& __m, adopt_lock_t) : _M_device(__m)
451 { } // calling thread owns mutex
454 { _M_device.unlock(); }
456 lock_guard(const lock_guard&) = delete;
457 lock_guard& operator=(const lock_guard&) = delete;
460 mutex_type& _M_device;
464 template<typename _Mutex>
468 typedef _Mutex mutex_type;
470 unique_lock() noexcept
471 : _M_device(0), _M_owns(false)
474 explicit unique_lock(mutex_type& __m)
475 : _M_device(&__m), _M_owns(false)
481 unique_lock(mutex_type& __m, defer_lock_t) noexcept
482 : _M_device(&__m), _M_owns(false)
485 unique_lock(mutex_type& __m, try_to_lock_t)
486 : _M_device(&__m), _M_owns(_M_device->try_lock())
489 unique_lock(mutex_type& __m, adopt_lock_t)
490 : _M_device(&__m), _M_owns(true)
492 // XXX calling thread owns mutex
495 template<typename _Clock, typename _Duration>
496 unique_lock(mutex_type& __m,
497 const chrono::time_point<_Clock, _Duration>& __atime)
498 : _M_device(&__m), _M_owns(_M_device->try_lock_until(__atime))
501 template<typename _Rep, typename _Period>
502 unique_lock(mutex_type& __m,
503 const chrono::duration<_Rep, _Period>& __rtime)
504 : _M_device(&__m), _M_owns(_M_device->try_lock_for(__rtime))
513 unique_lock(const unique_lock&) = delete;
514 unique_lock& operator=(const unique_lock&) = delete;
516 unique_lock(unique_lock&& __u) noexcept
517 : _M_device(__u._M_device), _M_owns(__u._M_owns)
523 unique_lock& operator=(unique_lock&& __u) noexcept
528 unique_lock(std::move(__u)).swap(*this);
540 __throw_system_error(int(errc::operation_not_permitted));
542 __throw_system_error(int(errc::resource_deadlock_would_occur));
554 __throw_system_error(int(errc::operation_not_permitted));
556 __throw_system_error(int(errc::resource_deadlock_would_occur));
559 _M_owns = _M_device->try_lock();
564 template<typename _Clock, typename _Duration>
566 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
569 __throw_system_error(int(errc::operation_not_permitted));
571 __throw_system_error(int(errc::resource_deadlock_would_occur));
574 _M_owns = _M_device->try_lock_until(__atime);
579 template<typename _Rep, typename _Period>
581 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
584 __throw_system_error(int(errc::operation_not_permitted));
586 __throw_system_error(int(errc::resource_deadlock_would_occur));
589 _M_owns = _M_device->try_lock_for(__rtime);
598 __throw_system_error(int(errc::operation_not_permitted));
607 swap(unique_lock& __u) noexcept
609 std::swap(_M_device, __u._M_device);
610 std::swap(_M_owns, __u._M_owns);
616 mutex_type* __ret = _M_device;
623 owns_lock() const noexcept
626 explicit operator bool() const noexcept
627 { return owns_lock(); }
630 mutex() const noexcept
631 { return _M_device; }
634 mutex_type* _M_device;
635 bool _M_owns; // XXX use atomic_bool
638 /// Partial specialization for unique_lock objects.
639 template<typename _Mutex>
641 swap(unique_lock<_Mutex>& __x, unique_lock<_Mutex>& __y) noexcept
647 template<typename... _Lock>
649 __do_unlock(tuple<_Lock&...>& __locks)
651 std::get<_Idx>(__locks).unlock();
652 __unlock_impl<_Idx - 1>::__do_unlock(__locks);
657 struct __unlock_impl<-1>
659 template<typename... _Lock>
661 __do_unlock(tuple<_Lock&...>&)
665 template<typename _Lock>
667 __try_to_lock(_Lock& __l)
668 { return unique_lock<_Lock>(__l, try_to_lock); }
670 template<int _Idx, bool _Continue = true>
671 struct __try_lock_impl
673 template<typename... _Lock>
675 __do_try_lock(tuple<_Lock&...>& __locks, int& __idx)
678 auto __lock = __try_to_lock(std::get<_Idx>(__locks));
679 if (__lock.owns_lock())
681 __try_lock_impl<_Idx + 1, _Idx + 2 < sizeof...(_Lock)>::
682 __do_try_lock(__locks, __idx);
690 struct __try_lock_impl<_Idx, false>
692 template<typename... _Lock>
694 __do_try_lock(tuple<_Lock&...>& __locks, int& __idx)
697 auto __lock = __try_to_lock(std::get<_Idx>(__locks));
698 if (__lock.owns_lock())
706 /** @brief Generic try_lock.
707 * @param __l1 Meets Mutex requirements (try_lock() may throw).
708 * @param __l2 Meets Mutex requirements (try_lock() may throw).
709 * @param __l3 Meets Mutex requirements (try_lock() may throw).
710 * @return Returns -1 if all try_lock() calls return true. Otherwise returns
711 * a 0-based index corresponding to the argument that returned false.
712 * @post Either all arguments are locked, or none will be.
714 * Sequentially calls try_lock() on each argument.
716 template<typename _Lock1, typename _Lock2, typename... _Lock3>
718 try_lock(_Lock1& __l1, _Lock2& __l2, _Lock3&... __l3)
721 auto __locks = std::tie(__l1, __l2, __l3...);
723 { __try_lock_impl<0>::__do_try_lock(__locks, __idx); }
729 /** @brief Generic lock.
730 * @param __l1 Meets Mutex requirements (try_lock() may throw).
731 * @param __l2 Meets Mutex requirements (try_lock() may throw).
732 * @param __l3 Meets Mutex requirements (try_lock() may throw).
733 * @throw An exception thrown by an argument's lock() or try_lock() member.
734 * @post All arguments are locked.
736 * All arguments are locked via a sequence of calls to lock(), try_lock()
737 * and unlock(). If the call exits via an exception any locks that were
738 * obtained will be released.
740 template<typename _L1, typename _L2, typename ..._L3>
742 lock(_L1& __l1, _L2& __l2, _L3&... __l3)
746 unique_lock<_L1> __first(__l1);
748 auto __locks = std::tie(__l2, __l3...);
749 __try_lock_impl<0, sizeof...(_L3)>::__do_try_lock(__locks, __idx);
762 typedef __gthread_once_t __native_type;
763 __native_type _M_once = __GTHREAD_ONCE_INIT;
767 constexpr once_flag() noexcept = default;
769 /// Deleted copy constructor
770 once_flag(const once_flag&) = delete;
771 /// Deleted assignment operator
772 once_flag& operator=(const once_flag&) = delete;
774 template<typename _Callable, typename... _Args>
776 call_once(once_flag& __once, _Callable&& __f, _Args&&... __args);
779 #ifdef _GLIBCXX_HAVE_TLS
780 extern __thread void* __once_callable;
781 extern __thread void (*__once_call)();
783 template<typename _Callable>
787 (*(_Callable*)__once_callable)();
790 extern function<void()> __once_functor;
793 __set_once_functor_lock_ptr(unique_lock<mutex>*);
799 extern "C" void __once_proxy(void);
802 template<typename _Callable, typename... _Args>
804 call_once(once_flag& __once, _Callable&& __f, _Args&&... __args)
806 #ifdef _GLIBCXX_HAVE_TLS
807 auto __bound_functor = std::__bind_simple(std::forward<_Callable>(__f),
808 std::forward<_Args>(__args)...);
809 __once_callable = &__bound_functor;
810 __once_call = &__once_call_impl<decltype(__bound_functor)>;
812 unique_lock<mutex> __functor_lock(__get_once_mutex());
813 auto __callable = std::__bind_simple(std::forward<_Callable>(__f),
814 std::forward<_Args>(__args)...);
815 __once_functor = [&]() { __callable(); };
816 __set_once_functor_lock_ptr(&__functor_lock);
819 int __e = __gthread_once(&(__once._M_once), &__once_proxy);
821 #ifndef _GLIBCXX_HAVE_TLS
823 __set_once_functor_lock_ptr(0);
827 __throw_system_error(__e);
831 _GLIBCXX_END_NAMESPACE_VERSION
834 #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1
836 #endif // __GXX_EXPERIMENTAL_CXX0X__
838 #endif // _GLIBCXX_MUTEX