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
56 * @defgroup mutexes Mutexes
57 * @ingroup concurrency
59 * Classes for mutex support.
66 typedef __gthread_mutex_t __native_type;
67 __native_type _M_mutex;
70 typedef __native_type* native_handle_type;
72 #ifdef __GTHREAD_MUTEX_INIT
73 constexpr mutex() noexcept : _M_mutex(__GTHREAD_MUTEX_INIT) { }
77 // XXX EAGAIN, ENOMEM, EPERM, EBUSY(may), EINVAL(may)
78 __GTHREAD_MUTEX_INIT_FUNCTION(&_M_mutex);
81 ~mutex() { __gthread_mutex_destroy(&_M_mutex); }
84 mutex(const mutex&) = delete;
85 mutex& operator=(const mutex&) = delete;
90 int __e = __gthread_mutex_lock(&_M_mutex);
92 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
94 __throw_system_error(__e);
100 // XXX EINVAL, EAGAIN, EBUSY
101 return !__gthread_mutex_trylock(&_M_mutex);
107 // XXX EINVAL, EAGAIN, EPERM
108 __gthread_mutex_unlock(&_M_mutex);
113 { return &_M_mutex; }
116 #ifndef __GTHREAD_RECURSIVE_MUTEX_INIT
117 // FIXME: gthreads doesn't define __gthread_recursive_mutex_destroy
118 // so we need to obtain a __gthread_mutex_t to destroy
119 class __destroy_recursive_mutex
121 template<typename _Mx, typename _Rm>
123 _S_destroy_win32(_Mx* __mx, _Rm const* __rmx)
125 __mx->counter = __rmx->counter;
126 __mx->sema = __rmx->sema;
127 __gthread_mutex_destroy(__mx);
131 // matches a gthr-win32.h recursive mutex
132 template<typename _Rm>
133 static typename enable_if<sizeof(&_Rm::sema), void>::type
134 _S_destroy(_Rm* __mx)
136 __gthread_mutex_t __tmp;
137 _S_destroy_win32(&__tmp, __mx);
140 // matches a recursive mutex with a member 'actual'
141 template<typename _Rm>
142 static typename enable_if<sizeof(&_Rm::actual), void>::type
143 _S_destroy(_Rm* __mx)
144 { __gthread_mutex_destroy(&__mx->actual); }
146 // matches when there's only one mutex type
147 template<typename _Rm>
149 typename enable_if<is_same<_Rm, __gthread_mutex_t>::value, void>::type
150 _S_destroy(_Rm* __mx)
151 { __gthread_mutex_destroy(__mx); }
156 class recursive_mutex
158 typedef __gthread_recursive_mutex_t __native_type;
159 __native_type _M_mutex;
162 typedef __native_type* native_handle_type;
164 #ifdef __GTHREAD_RECURSIVE_MUTEX_INIT
165 recursive_mutex() : _M_mutex(__GTHREAD_RECURSIVE_MUTEX_INIT) { }
169 // XXX EAGAIN, ENOMEM, EPERM, EBUSY(may), EINVAL(may)
170 __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION(&_M_mutex);
174 { __destroy_recursive_mutex::_S_destroy(&_M_mutex); }
177 recursive_mutex(const recursive_mutex&) = delete;
178 recursive_mutex& operator=(const recursive_mutex&) = delete;
183 int __e = __gthread_recursive_mutex_lock(&_M_mutex);
185 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
187 __throw_system_error(__e);
193 // XXX EINVAL, EAGAIN, EBUSY
194 return !__gthread_recursive_mutex_trylock(&_M_mutex);
200 // XXX EINVAL, EAGAIN, EBUSY
201 __gthread_recursive_mutex_unlock(&_M_mutex);
206 { return &_M_mutex; }
209 #if _GTHREAD_USE_MUTEX_TIMEDLOCK
213 typedef __gthread_mutex_t __native_type;
215 #ifdef _GLIBCXX_USE_CLOCK_MONOTONIC
216 typedef chrono::steady_clock __clock_t;
218 typedef chrono::high_resolution_clock __clock_t;
221 __native_type _M_mutex;
224 typedef __native_type* native_handle_type;
226 #ifdef __GTHREAD_MUTEX_INIT
227 timed_mutex() : _M_mutex(__GTHREAD_MUTEX_INIT) { }
231 __GTHREAD_MUTEX_INIT_FUNCTION(&_M_mutex);
234 ~timed_mutex() { __gthread_mutex_destroy(&_M_mutex); }
237 timed_mutex(const timed_mutex&) = delete;
238 timed_mutex& operator=(const timed_mutex&) = delete;
243 int __e = __gthread_mutex_lock(&_M_mutex);
245 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
247 __throw_system_error(__e);
253 // XXX EINVAL, EAGAIN, EBUSY
254 return !__gthread_mutex_trylock(&_M_mutex);
257 template <class _Rep, class _Period>
259 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
260 { return __try_lock_for_impl(__rtime); }
262 template <class _Clock, class _Duration>
264 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
266 chrono::time_point<_Clock, chrono::seconds> __s =
267 chrono::time_point_cast<chrono::seconds>(__atime);
269 chrono::nanoseconds __ns =
270 chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
272 __gthread_time_t __ts = {
273 static_cast<std::time_t>(__s.time_since_epoch().count()),
274 static_cast<long>(__ns.count())
277 return !__gthread_mutex_timedlock(&_M_mutex, &__ts);
283 // XXX EINVAL, EAGAIN, EBUSY
284 __gthread_mutex_unlock(&_M_mutex);
289 { return &_M_mutex; }
292 template<typename _Rep, typename _Period>
294 ratio_less_equal<__clock_t::period, _Period>::value, bool>::type
295 __try_lock_for_impl(const chrono::duration<_Rep, _Period>& __rtime)
297 __clock_t::time_point __atime = __clock_t::now()
298 + chrono::duration_cast<__clock_t::duration>(__rtime);
300 return try_lock_until(__atime);
303 template <typename _Rep, typename _Period>
305 !ratio_less_equal<__clock_t::period, _Period>::value, bool>::type
306 __try_lock_for_impl(const chrono::duration<_Rep, _Period>& __rtime)
308 __clock_t::time_point __atime = __clock_t::now()
309 + ++chrono::duration_cast<__clock_t::duration>(__rtime);
311 return try_lock_until(__atime);
315 /// recursive_timed_mutex
316 class recursive_timed_mutex
318 typedef __gthread_recursive_mutex_t __native_type;
320 #ifdef _GLIBCXX_USE_CLOCK_MONOTONIC
321 typedef chrono::steady_clock __clock_t;
323 typedef chrono::high_resolution_clock __clock_t;
326 __native_type _M_mutex;
329 typedef __native_type* native_handle_type;
331 #ifdef __GTHREAD_RECURSIVE_MUTEX_INIT
332 recursive_timed_mutex() : _M_mutex(__GTHREAD_RECURSIVE_MUTEX_INIT) { }
334 recursive_timed_mutex()
336 // XXX EAGAIN, ENOMEM, EPERM, EBUSY(may), EINVAL(may)
337 __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION(&_M_mutex);
340 ~recursive_timed_mutex()
341 { __destroy_recursive_mutex::_S_destroy(&_M_mutex); }
344 recursive_timed_mutex(const recursive_timed_mutex&) = delete;
345 recursive_timed_mutex& operator=(const recursive_timed_mutex&) = delete;
350 int __e = __gthread_recursive_mutex_lock(&_M_mutex);
352 // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
354 __throw_system_error(__e);
360 // XXX EINVAL, EAGAIN, EBUSY
361 return !__gthread_recursive_mutex_trylock(&_M_mutex);
364 template <class _Rep, class _Period>
366 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
367 { return __try_lock_for_impl(__rtime); }
369 template <class _Clock, class _Duration>
371 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
373 chrono::time_point<_Clock, chrono::seconds> __s =
374 chrono::time_point_cast<chrono::seconds>(__atime);
376 chrono::nanoseconds __ns =
377 chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
379 __gthread_time_t __ts = {
380 static_cast<std::time_t>(__s.time_since_epoch().count()),
381 static_cast<long>(__ns.count())
384 return !__gthread_recursive_mutex_timedlock(&_M_mutex, &__ts);
390 // XXX EINVAL, EAGAIN, EBUSY
391 __gthread_recursive_mutex_unlock(&_M_mutex);
396 { return &_M_mutex; }
399 template<typename _Rep, typename _Period>
401 ratio_less_equal<__clock_t::period, _Period>::value, bool>::type
402 __try_lock_for_impl(const chrono::duration<_Rep, _Period>& __rtime)
404 __clock_t::time_point __atime = __clock_t::now()
405 + chrono::duration_cast<__clock_t::duration>(__rtime);
407 return try_lock_until(__atime);
410 template <typename _Rep, typename _Period>
412 !ratio_less_equal<__clock_t::period, _Period>::value, bool>::type
413 __try_lock_for_impl(const chrono::duration<_Rep, _Period>& __rtime)
415 __clock_t::time_point __atime = __clock_t::now()
416 + ++chrono::duration_cast<__clock_t::duration>(__rtime);
418 return try_lock_until(__atime);
423 /// Do not acquire ownership of the mutex.
424 struct defer_lock_t { };
426 /// Try to acquire ownership of the mutex without blocking.
427 struct try_to_lock_t { };
429 /// Assume the calling thread has already obtained mutex ownership
431 struct adopt_lock_t { };
433 constexpr defer_lock_t defer_lock { };
434 constexpr try_to_lock_t try_to_lock { };
435 constexpr adopt_lock_t adopt_lock { };
437 /// @brief Scoped lock idiom.
438 // Acquire the mutex here with a constructor call, then release with
439 // the destructor call in accordance with RAII style.
440 template<typename _Mutex>
444 typedef _Mutex mutex_type;
446 explicit lock_guard(mutex_type& __m) : _M_device(__m)
447 { _M_device.lock(); }
449 lock_guard(mutex_type& __m, adopt_lock_t) : _M_device(__m)
450 { } // calling thread owns mutex
453 { _M_device.unlock(); }
455 lock_guard(const lock_guard&) = delete;
456 lock_guard& operator=(const lock_guard&) = delete;
459 mutex_type& _M_device;
463 template<typename _Mutex>
467 typedef _Mutex mutex_type;
469 unique_lock() noexcept
470 : _M_device(0), _M_owns(false)
473 explicit unique_lock(mutex_type& __m)
474 : _M_device(&__m), _M_owns(false)
480 unique_lock(mutex_type& __m, defer_lock_t) noexcept
481 : _M_device(&__m), _M_owns(false)
484 unique_lock(mutex_type& __m, try_to_lock_t)
485 : _M_device(&__m), _M_owns(_M_device->try_lock())
488 unique_lock(mutex_type& __m, adopt_lock_t)
489 : _M_device(&__m), _M_owns(true)
491 // XXX calling thread owns mutex
494 template<typename _Clock, typename _Duration>
495 unique_lock(mutex_type& __m,
496 const chrono::time_point<_Clock, _Duration>& __atime)
497 : _M_device(&__m), _M_owns(_M_device->try_lock_until(__atime))
500 template<typename _Rep, typename _Period>
501 unique_lock(mutex_type& __m,
502 const chrono::duration<_Rep, _Period>& __rtime)
503 : _M_device(&__m), _M_owns(_M_device->try_lock_for(__rtime))
512 unique_lock(const unique_lock&) = delete;
513 unique_lock& operator=(const unique_lock&) = delete;
515 unique_lock(unique_lock&& __u) noexcept
516 : _M_device(__u._M_device), _M_owns(__u._M_owns)
522 unique_lock& operator=(unique_lock&& __u) noexcept
527 unique_lock(std::move(__u)).swap(*this);
539 __throw_system_error(int(errc::operation_not_permitted));
541 __throw_system_error(int(errc::resource_deadlock_would_occur));
553 __throw_system_error(int(errc::operation_not_permitted));
555 __throw_system_error(int(errc::resource_deadlock_would_occur));
558 _M_owns = _M_device->try_lock();
563 template<typename _Clock, typename _Duration>
565 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
568 __throw_system_error(int(errc::operation_not_permitted));
570 __throw_system_error(int(errc::resource_deadlock_would_occur));
573 _M_owns = _M_device->try_lock_until(__atime);
578 template<typename _Rep, typename _Period>
580 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
583 __throw_system_error(int(errc::operation_not_permitted));
585 __throw_system_error(int(errc::resource_deadlock_would_occur));
588 _M_owns = _M_device->try_lock_for(__rtime);
597 __throw_system_error(int(errc::operation_not_permitted));
606 swap(unique_lock& __u) noexcept
608 std::swap(_M_device, __u._M_device);
609 std::swap(_M_owns, __u._M_owns);
615 mutex_type* __ret = _M_device;
622 owns_lock() const noexcept
625 explicit operator bool() const noexcept
626 { return owns_lock(); }
629 mutex() const noexcept
630 { return _M_device; }
633 mutex_type* _M_device;
634 bool _M_owns; // XXX use atomic_bool
637 /// Partial specialization for unique_lock objects.
638 template<typename _Mutex>
640 swap(unique_lock<_Mutex>& __x, unique_lock<_Mutex>& __y) noexcept
646 template<typename... _Lock>
648 __do_unlock(tuple<_Lock&...>& __locks)
650 std::get<_Idx>(__locks).unlock();
651 __unlock_impl<_Idx - 1>::__do_unlock(__locks);
656 struct __unlock_impl<-1>
658 template<typename... _Lock>
660 __do_unlock(tuple<_Lock&...>&)
664 template<typename _Lock>
666 __try_to_lock(_Lock& __l)
667 { return unique_lock<_Lock>(__l, try_to_lock); }
669 template<int _Idx, bool _Continue = true>
670 struct __try_lock_impl
672 template<typename... _Lock>
674 __do_try_lock(tuple<_Lock&...>& __locks, int& __idx)
677 auto __lock = __try_to_lock(std::get<_Idx>(__locks));
678 if (__lock.owns_lock())
680 __try_lock_impl<_Idx + 1, _Idx + 2 < sizeof...(_Lock)>::
681 __do_try_lock(__locks, __idx);
689 struct __try_lock_impl<_Idx, false>
691 template<typename... _Lock>
693 __do_try_lock(tuple<_Lock&...>& __locks, int& __idx)
696 auto __lock = __try_to_lock(std::get<_Idx>(__locks));
697 if (__lock.owns_lock())
705 /** @brief Generic try_lock.
706 * @param __l1 Meets Mutex requirements (try_lock() may throw).
707 * @param __l2 Meets Mutex requirements (try_lock() may throw).
708 * @param __l3 Meets Mutex requirements (try_lock() may throw).
709 * @return Returns -1 if all try_lock() calls return true. Otherwise returns
710 * a 0-based index corresponding to the argument that returned false.
711 * @post Either all arguments are locked, or none will be.
713 * Sequentially calls try_lock() on each argument.
715 template<typename _Lock1, typename _Lock2, typename... _Lock3>
717 try_lock(_Lock1& __l1, _Lock2& __l2, _Lock3&... __l3)
720 auto __locks = std::tie(__l1, __l2, __l3...);
722 { __try_lock_impl<0>::__do_try_lock(__locks, __idx); }
728 /** @brief Generic lock.
729 * @param __l1 Meets Mutex requirements (try_lock() may throw).
730 * @param __l2 Meets Mutex requirements (try_lock() may throw).
731 * @param __l3 Meets Mutex requirements (try_lock() may throw).
732 * @throw An exception thrown by an argument's lock() or try_lock() member.
733 * @post All arguments are locked.
735 * All arguments are locked via a sequence of calls to lock(), try_lock()
736 * and unlock(). If the call exits via an exception any locks that were
737 * obtained will be released.
739 template<typename _L1, typename _L2, typename ..._L3>
741 lock(_L1& __l1, _L2& __l2, _L3&... __l3)
745 unique_lock<_L1> __first(__l1);
747 auto __locks = std::tie(__l2, __l3...);
748 __try_lock_impl<0, sizeof...(_L3)>::__do_try_lock(__locks, __idx);
761 typedef __gthread_once_t __native_type;
762 __native_type _M_once;
766 constexpr once_flag() noexcept : _M_once(__GTHREAD_ONCE_INIT) { }
768 /// Deleted copy constructor
769 once_flag(const once_flag&) = delete;
770 /// Deleted assignment operator
771 once_flag& operator=(const once_flag&) = delete;
773 template<typename _Callable, typename... _Args>
775 call_once(once_flag& __once, _Callable&& __f, _Args&&... __args);
778 #ifdef _GLIBCXX_HAVE_TLS
779 extern __thread void* __once_callable;
780 extern __thread void (*__once_call)();
782 template<typename _Callable>
786 (*(_Callable*)__once_callable)();
789 extern function<void()> __once_functor;
792 __set_once_functor_lock_ptr(unique_lock<mutex>*);
798 extern "C" void __once_proxy();
801 template<typename _Callable, typename... _Args>
803 call_once(once_flag& __once, _Callable&& __f, _Args&&... __args)
805 #ifdef _GLIBCXX_HAVE_TLS
806 auto __bound_functor = std::__bind_simple(std::forward<_Callable>(__f),
807 std::forward<_Args>(__args)...);
808 __once_callable = &__bound_functor;
809 __once_call = &__once_call_impl<decltype(__bound_functor)>;
811 unique_lock<mutex> __functor_lock(__get_once_mutex());
812 __once_functor = std::__bind_simple(std::forward<_Callable>(__f),
813 std::forward<_Args>(__args)...);
814 __set_once_functor_lock_ptr(&__functor_lock);
817 int __e = __gthread_once(&(__once._M_once), &__once_proxy);
819 #ifndef _GLIBCXX_HAVE_TLS
821 __set_once_functor_lock_ptr(0);
825 __throw_system_error(__e);
829 _GLIBCXX_END_NAMESPACE_VERSION
832 #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1
834 #endif // __GXX_EXPERIMENTAL_CXX0X__
836 #endif // _GLIBCXX_MUTEX