3 // Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
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 _GLIBCXX_BEGIN_NAMESPACE(std)
54 * @defgroup mutexes Mutexes
55 * @ingroup concurrency
57 * Classes for mutex support.
64 typedef __gthread_mutex_t __native_type;
65 __native_type _M_mutex;
68 typedef __native_type* native_handle_type;
70 #ifdef __GTHREAD_MUTEX_INIT
71 constexpr mutex() : _M_mutex(__GTHREAD_MUTEX_INIT) { }
75 // XXX EAGAIN, ENOMEM, EPERM, EBUSY(may), EINVAL(may)
76 __GTHREAD_MUTEX_INIT_FUNCTION(&_M_mutex);
79 ~mutex() { __gthread_mutex_destroy(&_M_mutex); }
82 mutex(const mutex&) = delete;
83 mutex& operator=(const mutex&) = delete;
88 int __e = __gthread_mutex_lock(&_M_mutex);
90 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
92 __throw_system_error(__e);
98 // XXX EINVAL, EAGAIN, EBUSY
99 return !__gthread_mutex_trylock(&_M_mutex);
105 // XXX EINVAL, EAGAIN, EPERM
106 __gthread_mutex_unlock(&_M_mutex);
111 { return &_M_mutex; }
114 #ifndef __GTHREAD_RECURSIVE_MUTEX_INIT
115 // FIXME: gthreads doesn't define __gthread_recursive_mutex_destroy
116 // so we need to obtain a __gthread_mutex_t to destroy
117 class __destroy_recursive_mutex
119 template<typename _Mx, typename _Rm>
121 _S_destroy_win32(_Mx* __mx, _Rm const* __rmx)
123 __mx->counter = __rmx->counter;
124 __mx->sema = __rmx->sema;
125 __gthread_mutex_destroy(__mx);
129 // matches a gthr-win32.h recursive mutex
130 template<typename _Rm>
131 static typename enable_if<sizeof(&_Rm::sema), void>::type
132 _S_destroy(_Rm* __mx)
134 __gthread_mutex_t __tmp;
135 _S_destroy_win32(&__tmp, __mx);
138 // matches a recursive mutex with a member 'actual'
139 template<typename _Rm>
140 static typename enable_if<sizeof(&_Rm::actual), void>::type
141 _S_destroy(_Rm* __mx)
142 { __gthread_mutex_destroy(&__mx->actual); }
144 // matches when there's only one mutex type
145 template<typename _Rm>
147 typename enable_if<is_same<_Rm, __gthread_mutex_t>::value, void>::type
148 _S_destroy(_Rm* __mx)
149 { __gthread_mutex_destroy(__mx); }
154 class recursive_mutex
156 typedef __gthread_recursive_mutex_t __native_type;
157 __native_type _M_mutex;
160 typedef __native_type* native_handle_type;
162 #ifdef __GTHREAD_RECURSIVE_MUTEX_INIT
163 recursive_mutex() : _M_mutex(__GTHREAD_RECURSIVE_MUTEX_INIT) { }
167 // XXX EAGAIN, ENOMEM, EPERM, EBUSY(may), EINVAL(may)
168 __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION(&_M_mutex);
172 { __destroy_recursive_mutex::_S_destroy(&_M_mutex); }
175 recursive_mutex(const recursive_mutex&) = delete;
176 recursive_mutex& operator=(const recursive_mutex&) = delete;
181 int __e = __gthread_recursive_mutex_lock(&_M_mutex);
183 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
185 __throw_system_error(__e);
191 // XXX EINVAL, EAGAIN, EBUSY
192 return !__gthread_recursive_mutex_trylock(&_M_mutex);
198 // XXX EINVAL, EAGAIN, EBUSY
199 __gthread_recursive_mutex_unlock(&_M_mutex);
204 { return &_M_mutex; }
210 typedef __gthread_mutex_t __native_type;
212 #ifdef _GLIBCXX_USE_CLOCK_MONOTONIC
213 typedef chrono::monotonic_clock __clock_t;
215 typedef chrono::high_resolution_clock __clock_t;
218 __native_type _M_mutex;
221 typedef __native_type* native_handle_type;
223 #ifdef __GTHREAD_MUTEX_INIT
224 timed_mutex() : _M_mutex(__GTHREAD_MUTEX_INIT) { }
228 __GTHREAD_MUTEX_INIT_FUNCTION(&_M_mutex);
231 ~timed_mutex() { __gthread_mutex_destroy(&_M_mutex); }
234 timed_mutex(const timed_mutex&) = delete;
235 timed_mutex& operator=(const timed_mutex&) = delete;
240 int __e = __gthread_mutex_lock(&_M_mutex);
242 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
244 __throw_system_error(__e);
250 // XXX EINVAL, EAGAIN, EBUSY
251 return !__gthread_mutex_trylock(&_M_mutex);
254 template <class _Rep, class _Period>
256 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
257 { return __try_lock_for_impl(__rtime); }
259 template <class _Clock, class _Duration>
261 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
263 chrono::time_point<_Clock, chrono::seconds> __s =
264 chrono::time_point_cast<chrono::seconds>(__atime);
266 chrono::nanoseconds __ns =
267 chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
269 __gthread_time_t __ts = {
270 static_cast<std::time_t>(__s.time_since_epoch().count()),
271 static_cast<long>(__ns.count())
274 return !__gthread_mutex_timedlock(&_M_mutex, &__ts);
280 // XXX EINVAL, EAGAIN, EBUSY
281 __gthread_mutex_unlock(&_M_mutex);
286 { return &_M_mutex; }
289 template<typename _Rep, typename _Period>
291 ratio_less_equal<__clock_t::period, _Period>::value, bool>::type
292 __try_lock_for_impl(const chrono::duration<_Rep, _Period>& __rtime)
294 __clock_t::time_point __atime = __clock_t::now()
295 + chrono::duration_cast<__clock_t::duration>(__rtime);
297 return try_lock_until(__atime);
300 template <typename _Rep, typename _Period>
302 !ratio_less_equal<__clock_t::period, _Period>::value, bool>::type
303 __try_lock_for_impl(const chrono::duration<_Rep, _Period>& __rtime)
305 __clock_t::time_point __atime = __clock_t::now()
306 + ++chrono::duration_cast<__clock_t::duration>(__rtime);
308 return try_lock_until(__atime);
312 /// recursive_timed_mutex
313 class recursive_timed_mutex
315 typedef __gthread_recursive_mutex_t __native_type;
317 #ifdef _GLIBCXX_USE_CLOCK_MONOTONIC
318 typedef chrono::monotonic_clock __clock_t;
320 typedef chrono::high_resolution_clock __clock_t;
323 __native_type _M_mutex;
326 typedef __native_type* native_handle_type;
328 #ifdef __GTHREAD_RECURSIVE_MUTEX_INIT
329 recursive_timed_mutex() : _M_mutex(__GTHREAD_RECURSIVE_MUTEX_INIT) { }
331 recursive_timed_mutex()
333 // XXX EAGAIN, ENOMEM, EPERM, EBUSY(may), EINVAL(may)
334 __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION(&_M_mutex);
337 ~recursive_timed_mutex()
338 { __destroy_recursive_mutex::_S_destroy(&_M_mutex); }
341 recursive_timed_mutex(const recursive_timed_mutex&) = delete;
342 recursive_timed_mutex& operator=(const recursive_timed_mutex&) = delete;
347 int __e = __gthread_recursive_mutex_lock(&_M_mutex);
349 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
351 __throw_system_error(__e);
357 // XXX EINVAL, EAGAIN, EBUSY
358 return !__gthread_recursive_mutex_trylock(&_M_mutex);
361 template <class _Rep, class _Period>
363 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
364 { return __try_lock_for_impl(__rtime); }
366 template <class _Clock, class _Duration>
368 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
370 chrono::time_point<_Clock, chrono::seconds> __s =
371 chrono::time_point_cast<chrono::seconds>(__atime);
373 chrono::nanoseconds __ns =
374 chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
376 __gthread_time_t __ts = {
377 static_cast<std::time_t>(__s.time_since_epoch().count()),
378 static_cast<long>(__ns.count())
381 return !__gthread_recursive_mutex_timedlock(&_M_mutex, &__ts);
387 // XXX EINVAL, EAGAIN, EBUSY
388 __gthread_recursive_mutex_unlock(&_M_mutex);
393 { return &_M_mutex; }
396 template<typename _Rep, typename _Period>
398 ratio_less_equal<__clock_t::period, _Period>::value, bool>::type
399 __try_lock_for_impl(const chrono::duration<_Rep, _Period>& __rtime)
401 __clock_t::time_point __atime = __clock_t::now()
402 + chrono::duration_cast<__clock_t::duration>(__rtime);
404 return try_lock_until(__atime);
407 template <typename _Rep, typename _Period>
409 !ratio_less_equal<__clock_t::period, _Period>::value, bool>::type
410 __try_lock_for_impl(const chrono::duration<_Rep, _Period>& __rtime)
412 __clock_t::time_point __atime = __clock_t::now()
413 + ++chrono::duration_cast<__clock_t::duration>(__rtime);
415 return try_lock_until(__atime);
419 /// Do not acquire ownership of the mutex.
420 struct defer_lock_t { };
422 /// Try to acquire ownership of the mutex without blocking.
423 struct try_to_lock_t { };
425 /// Assume the calling thread has already obtained mutex ownership
427 struct adopt_lock_t { };
429 constexpr defer_lock_t defer_lock { };
430 constexpr try_to_lock_t try_to_lock { };
431 constexpr adopt_lock_t adopt_lock { };
433 /// @brief Scoped lock idiom.
434 // Acquire the mutex here with a constructor call, then release with
435 // the destructor call in accordance with RAII style.
436 template<typename _Mutex>
440 typedef _Mutex mutex_type;
442 explicit lock_guard(mutex_type& __m) : _M_device(__m)
443 { _M_device.lock(); }
445 lock_guard(mutex_type& __m, adopt_lock_t) : _M_device(__m)
446 { } // calling thread owns mutex
449 { _M_device.unlock(); }
451 lock_guard(const lock_guard&) = delete;
452 lock_guard& operator=(const lock_guard&) = delete;
455 mutex_type& _M_device;
459 template<typename _Mutex>
463 typedef _Mutex mutex_type;
466 : _M_device(0), _M_owns(false)
469 explicit unique_lock(mutex_type& __m)
470 : _M_device(&__m), _M_owns(false)
476 unique_lock(mutex_type& __m, defer_lock_t)
477 : _M_device(&__m), _M_owns(false)
480 unique_lock(mutex_type& __m, try_to_lock_t)
481 : _M_device(&__m), _M_owns(_M_device->try_lock())
484 unique_lock(mutex_type& __m, adopt_lock_t)
485 : _M_device(&__m), _M_owns(true)
487 // XXX calling thread owns mutex
490 template<typename _Clock, typename _Duration>
491 unique_lock(mutex_type& __m,
492 const chrono::time_point<_Clock, _Duration>& __atime)
493 : _M_device(&__m), _M_owns(_M_device->try_lock_until(__atime))
496 template<typename _Rep, typename _Period>
497 unique_lock(mutex_type& __m,
498 const chrono::duration<_Rep, _Period>& __rtime)
499 : _M_device(&__m), _M_owns(_M_device->try_lock_for(__rtime))
508 unique_lock(const unique_lock&) = delete;
509 unique_lock& operator=(const unique_lock&) = delete;
511 unique_lock(unique_lock&& __u)
512 : _M_device(__u._M_device), _M_owns(__u._M_owns)
518 unique_lock& operator=(unique_lock&& __u)
523 unique_lock(std::move(__u)).swap(*this);
535 __throw_system_error(int(errc::operation_not_permitted));
537 __throw_system_error(int(errc::resource_deadlock_would_occur));
549 __throw_system_error(int(errc::operation_not_permitted));
551 __throw_system_error(int(errc::resource_deadlock_would_occur));
554 _M_owns = _M_device->try_lock();
559 template<typename _Clock, typename _Duration>
561 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
564 __throw_system_error(int(errc::operation_not_permitted));
566 __throw_system_error(int(errc::resource_deadlock_would_occur));
569 _M_owns = _M_device->try_lock_until(__atime);
574 template<typename _Rep, typename _Period>
576 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
579 __throw_system_error(int(errc::operation_not_permitted));
581 __throw_system_error(int(errc::resource_deadlock_would_occur));
584 _M_owns = _M_device->try_lock_for(__rtime);
593 __throw_system_error(int(errc::operation_not_permitted));
602 swap(unique_lock& __u)
604 std::swap(_M_device, __u._M_device);
605 std::swap(_M_owns, __u._M_owns);
611 mutex_type* __ret = _M_device;
621 explicit operator bool() const
622 { return owns_lock(); }
626 { return _M_device; }
629 mutex_type* _M_device;
630 bool _M_owns; // XXX use atomic_bool
633 template<typename _Mutex>
635 swap(unique_lock<_Mutex>& __x, unique_lock<_Mutex>& __y)
641 template<typename... _Lock>
643 __do_unlock(tuple<_Lock&...>& __locks)
645 std::get<_Idx>(__locks).unlock();
646 __unlock_impl<_Idx - 1>::__do_unlock(__locks);
651 struct __unlock_impl<-1>
653 template<typename... _Lock>
655 __do_unlock(tuple<_Lock&...>&)
659 template<typename _Lock>
661 __try_to_lock(_Lock& __l)
662 { return unique_lock<_Lock>(__l, try_to_lock); }
664 template<int _Idx, bool _Continue = true>
665 struct __try_lock_impl
667 template<typename... _Lock>
669 __do_try_lock(tuple<_Lock&...>& __locks, int& __idx)
672 auto __lock = __try_to_lock(std::get<_Idx>(__locks));
673 if (__lock.owns_lock())
675 __try_lock_impl<_Idx + 1, _Idx + 2 < sizeof...(_Lock)>::
676 __do_try_lock(__locks, __idx);
684 struct __try_lock_impl<_Idx, false>
686 template<typename... _Lock>
688 __do_try_lock(tuple<_Lock&...>& __locks, int& __idx)
691 auto __lock = __try_to_lock(std::get<_Idx>(__locks));
692 if (__lock.owns_lock())
700 /** @brief Generic try_lock.
701 * @param __l1 Meets Mutex requirements (try_lock() may throw).
702 * @param __l2 Meets Mutex requirements (try_lock() may throw).
703 * @param __l3 Meets Mutex requirements (try_lock() may throw).
704 * @return Returns -1 if all try_lock() calls return true. Otherwise returns
705 * a 0-based index corresponding to the argument that returned false.
706 * @post Either all arguments are locked, or none will be.
708 * Sequentially calls try_lock() on each argument.
710 template<typename _Lock1, typename _Lock2, typename... _Lock3>
712 try_lock(_Lock1& __l1, _Lock2& __l2, _Lock3&... __l3)
715 auto __locks = std::tie(__l1, __l2, __l3...);
717 { __try_lock_impl<0>::__do_try_lock(__locks, __idx); }
723 /** @brief Generic lock.
724 * @param __l1 Meets Mutex requirements (try_lock() may throw).
725 * @param __l2 Meets Mutex requirements (try_lock() may throw).
726 * @param __l3 Meets Mutex requirements (try_lock() may throw).
727 * @throw An exception thrown by an argument's lock() or try_lock() member.
728 * @post All arguments are locked.
730 * All arguments are locked via a sequence of calls to lock(), try_lock()
731 * and unlock(). If the call exits via an exception any locks that were
732 * obtained will be released.
734 template<typename _L1, typename _L2, typename ..._L3>
736 lock(_L1& __l1, _L2& __l2, _L3&... __l3)
740 unique_lock<_L1> __first(__l1);
742 auto __locks = std::tie(__l2, __l3...);
743 __try_lock_impl<0, sizeof...(_L3)>::__do_try_lock(__locks, __idx);
756 typedef __gthread_once_t __native_type;
757 __native_type _M_once;
760 constexpr once_flag() : _M_once(__GTHREAD_ONCE_INIT) { }
762 once_flag(const once_flag&) = delete;
763 once_flag& operator=(const once_flag&) = delete;
765 template<typename _Callable, typename... _Args>
767 call_once(once_flag& __once, _Callable&& __f, _Args&&... __args);
770 #ifdef _GLIBCXX_HAVE_TLS
771 extern __thread void* __once_callable;
772 extern __thread void (*__once_call)();
774 template<typename _Callable>
778 (*(_Callable*)__once_callable)();
781 extern function<void()> __once_functor;
784 __set_once_functor_lock_ptr(unique_lock<mutex>*);
790 extern "C" void __once_proxy();
793 template<typename _Callable, typename... _Args>
795 call_once(once_flag& __once, _Callable&& __f, _Args&&... __args)
797 #ifdef _GLIBCXX_HAVE_TLS
798 auto __bound_functor = std::bind<void>(std::forward<_Callable>(__f),
799 std::forward<_Args>(__args)...);
800 __once_callable = &__bound_functor;
801 __once_call = &__once_call_impl<decltype(__bound_functor)>;
803 unique_lock<mutex> __functor_lock(__get_once_mutex());
804 __once_functor = std::bind<void>(std::forward<_Callable>(__f),
805 std::forward<_Args>(__args)...);
806 __set_once_functor_lock_ptr(&__functor_lock);
809 int __e = __gthread_once(&(__once._M_once), &__once_proxy);
811 #ifndef _GLIBCXX_HAVE_TLS
813 __set_once_functor_lock_ptr(0);
817 __throw_system_error(__e);
821 _GLIBCXX_END_NAMESPACE
823 #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1
825 #endif // __GXX_EXPERIMENTAL_CXX0X__
827 #endif // _GLIBCXX_MUTEX