1// -*- C++ -*-
2//===----------------------------------------------------------------------===//
3//
4//                     The LLVM Compiler Infrastructure
5//
6// This file is dual licensed under the MIT and the University of Illinois Open
7// Source Licenses. See LICENSE.TXT for details.
8//
9//===----------------------------------------------------------------------===//
10
11#ifndef _LIBCPP___MUTEX_BASE
12#define _LIBCPP___MUTEX_BASE
13
14#include <__config>
15#include <chrono>
16#include <system_error>
17#if !defined(__minix)
18#include <pthread.h>
19#else
20#define _MTHREADIFY_PTHREADS 1
21#include <minix/mthread.h>
22#endif /* !defined(__minix) */
23
24#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
25#pragma GCC system_header
26#endif
27
28_LIBCPP_BEGIN_NAMESPACE_STD
29
30class _LIBCPP_TYPE_VIS mutex
31{
32    pthread_mutex_t __m_;
33
34public:
35    _LIBCPP_INLINE_VISIBILITY
36#ifndef _LIBCPP_HAS_NO_CONSTEXPR
37     constexpr mutex() _NOEXCEPT : __m_(PTHREAD_MUTEX_INITIALIZER) {}
38#else
39     mutex() _NOEXCEPT {__m_ = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;}
40#endif
41     ~mutex();
42
43private:
44    mutex(const mutex&);// = delete;
45    mutex& operator=(const mutex&);// = delete;
46
47public:
48    void lock();
49    bool try_lock() _NOEXCEPT;
50    void unlock() _NOEXCEPT;
51
52    typedef pthread_mutex_t* native_handle_type;
53    _LIBCPP_INLINE_VISIBILITY native_handle_type native_handle() {return &__m_;}
54};
55
56struct _LIBCPP_TYPE_VIS defer_lock_t {};
57struct _LIBCPP_TYPE_VIS try_to_lock_t {};
58struct _LIBCPP_TYPE_VIS adopt_lock_t {};
59
60#if defined(_LIBCPP_HAS_NO_CONSTEXPR) || defined(_LIBCPP_BUILDING_MUTEX)
61
62extern const defer_lock_t  defer_lock;
63extern const try_to_lock_t try_to_lock;
64extern const adopt_lock_t  adopt_lock;
65
66#else
67
68constexpr defer_lock_t  defer_lock  = defer_lock_t();
69constexpr try_to_lock_t try_to_lock = try_to_lock_t();
70constexpr adopt_lock_t  adopt_lock  = adopt_lock_t();
71
72#endif
73
74template <class _Mutex>
75class _LIBCPP_TYPE_VIS_ONLY lock_guard
76{
77public:
78    typedef _Mutex mutex_type;
79
80private:
81    mutex_type& __m_;
82public:
83
84    _LIBCPP_INLINE_VISIBILITY
85    explicit lock_guard(mutex_type& __m)
86        : __m_(__m) {__m_.lock();}
87    _LIBCPP_INLINE_VISIBILITY
88    lock_guard(mutex_type& __m, adopt_lock_t)
89        : __m_(__m) {}
90    _LIBCPP_INLINE_VISIBILITY
91    ~lock_guard() {__m_.unlock();}
92
93private:
94    lock_guard(lock_guard const&);// = delete;
95    lock_guard& operator=(lock_guard const&);// = delete;
96};
97
98template <class _Mutex>
99class _LIBCPP_TYPE_VIS_ONLY unique_lock
100{
101public:
102    typedef _Mutex mutex_type;
103
104private:
105    mutex_type* __m_;
106    bool __owns_;
107
108public:
109    _LIBCPP_INLINE_VISIBILITY
110    unique_lock() _NOEXCEPT : __m_(nullptr), __owns_(false) {}
111    _LIBCPP_INLINE_VISIBILITY
112    explicit unique_lock(mutex_type& __m)
113        : __m_(&__m), __owns_(true) {__m_->lock();}
114    _LIBCPP_INLINE_VISIBILITY
115    unique_lock(mutex_type& __m, defer_lock_t) _NOEXCEPT
116        : __m_(&__m), __owns_(false) {}
117    _LIBCPP_INLINE_VISIBILITY
118    unique_lock(mutex_type& __m, try_to_lock_t)
119        : __m_(&__m), __owns_(__m.try_lock()) {}
120    _LIBCPP_INLINE_VISIBILITY
121    unique_lock(mutex_type& __m, adopt_lock_t)
122        : __m_(&__m), __owns_(true) {}
123    template <class _Clock, class _Duration>
124    _LIBCPP_INLINE_VISIBILITY
125        unique_lock(mutex_type& __m, const chrono::time_point<_Clock, _Duration>& __t)
126            : __m_(&__m), __owns_(__m.try_lock_until(__t)) {}
127    template <class _Rep, class _Period>
128    _LIBCPP_INLINE_VISIBILITY
129        unique_lock(mutex_type& __m, const chrono::duration<_Rep, _Period>& __d)
130            : __m_(&__m), __owns_(__m.try_lock_for(__d)) {}
131    _LIBCPP_INLINE_VISIBILITY
132    ~unique_lock()
133    {
134        if (__owns_)
135            __m_->unlock();
136    }
137
138private:
139    unique_lock(unique_lock const&); // = delete;
140    unique_lock& operator=(unique_lock const&); // = delete;
141
142public:
143#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
144    _LIBCPP_INLINE_VISIBILITY
145    unique_lock(unique_lock&& __u) _NOEXCEPT
146        : __m_(__u.__m_), __owns_(__u.__owns_)
147        {__u.__m_ = nullptr; __u.__owns_ = false;}
148    _LIBCPP_INLINE_VISIBILITY
149    unique_lock& operator=(unique_lock&& __u) _NOEXCEPT
150        {
151            if (__owns_)
152                __m_->unlock();
153            __m_ = __u.__m_;
154            __owns_ = __u.__owns_;
155            __u.__m_ = nullptr;
156            __u.__owns_ = false;
157            return *this;
158        }
159
160#endif  // _LIBCPP_HAS_NO_RVALUE_REFERENCES
161
162    void lock();
163    bool try_lock();
164
165    template <class _Rep, class _Period>
166        bool try_lock_for(const chrono::duration<_Rep, _Period>& __d);
167    template <class _Clock, class _Duration>
168        bool try_lock_until(const chrono::time_point<_Clock, _Duration>& __t);
169
170    void unlock();
171
172    _LIBCPP_INLINE_VISIBILITY
173    void swap(unique_lock& __u) _NOEXCEPT
174    {
175        _VSTD::swap(__m_, __u.__m_);
176        _VSTD::swap(__owns_, __u.__owns_);
177    }
178    _LIBCPP_INLINE_VISIBILITY
179    mutex_type* release() _NOEXCEPT
180    {
181        mutex_type* __m = __m_;
182        __m_ = nullptr;
183        __owns_ = false;
184        return __m;
185    }
186
187    _LIBCPP_INLINE_VISIBILITY
188    bool owns_lock() const _NOEXCEPT {return __owns_;}
189    _LIBCPP_INLINE_VISIBILITY
190    _LIBCPP_EXPLICIT
191        operator bool () const _NOEXCEPT {return __owns_;}
192    _LIBCPP_INLINE_VISIBILITY
193    mutex_type* mutex() const _NOEXCEPT {return __m_;}
194};
195
196template <class _Mutex>
197void
198unique_lock<_Mutex>::lock()
199{
200    if (__m_ == nullptr)
201        __throw_system_error(EPERM, "unique_lock::lock: references null mutex");
202    if (__owns_)
203        __throw_system_error(EDEADLK, "unique_lock::lock: already locked");
204    __m_->lock();
205    __owns_ = true;
206}
207
208template <class _Mutex>
209bool
210unique_lock<_Mutex>::try_lock()
211{
212    if (__m_ == nullptr)
213        __throw_system_error(EPERM, "unique_lock::try_lock: references null mutex");
214    if (__owns_)
215        __throw_system_error(EDEADLK, "unique_lock::try_lock: already locked");
216    __owns_ = __m_->try_lock();
217    return __owns_;
218}
219
220template <class _Mutex>
221template <class _Rep, class _Period>
222bool
223unique_lock<_Mutex>::try_lock_for(const chrono::duration<_Rep, _Period>& __d)
224{
225    if (__m_ == nullptr)
226        __throw_system_error(EPERM, "unique_lock::try_lock_for: references null mutex");
227    if (__owns_)
228        __throw_system_error(EDEADLK, "unique_lock::try_lock_for: already locked");
229    __owns_ = __m_->try_lock_for(__d);
230    return __owns_;
231}
232
233template <class _Mutex>
234template <class _Clock, class _Duration>
235bool
236unique_lock<_Mutex>::try_lock_until(const chrono::time_point<_Clock, _Duration>& __t)
237{
238    if (__m_ == nullptr)
239        __throw_system_error(EPERM, "unique_lock::try_lock_until: references null mutex");
240    if (__owns_)
241        __throw_system_error(EDEADLK, "unique_lock::try_lock_until: already locked");
242    __owns_ = __m_->try_lock_until(__t);
243    return __owns_;
244}
245
246template <class _Mutex>
247void
248unique_lock<_Mutex>::unlock()
249{
250    if (!__owns_)
251        __throw_system_error(EPERM, "unique_lock::unlock: not locked");
252    __m_->unlock();
253    __owns_ = false;
254}
255
256template <class _Mutex>
257inline _LIBCPP_INLINE_VISIBILITY
258void
259swap(unique_lock<_Mutex>& __x, unique_lock<_Mutex>& __y) _NOEXCEPT
260    {__x.swap(__y);}
261
262struct _LIBCPP_TYPE_VIS cv_status
263{
264    enum __lx {
265        no_timeout,
266        timeout
267    };
268
269    __lx __v_;
270
271    _LIBCPP_INLINE_VISIBILITY cv_status(__lx __v) : __v_(__v) {}
272    _LIBCPP_INLINE_VISIBILITY operator int() const {return __v_;}
273
274};
275
276class _LIBCPP_TYPE_VIS condition_variable
277{
278    pthread_cond_t __cv_;
279public:
280    _LIBCPP_INLINE_VISIBILITY
281#ifndef _LIBCPP_HAS_NO_CONSTEXPR
282    constexpr condition_variable() : __cv_(PTHREAD_COND_INITIALIZER) {}
283#else
284    condition_variable() {__cv_ = (pthread_cond_t)PTHREAD_COND_INITIALIZER;}
285#endif
286    ~condition_variable();
287
288private:
289    condition_variable(const condition_variable&); // = delete;
290    condition_variable& operator=(const condition_variable&); // = delete;
291
292public:
293    void notify_one() _NOEXCEPT;
294    void notify_all() _NOEXCEPT;
295
296    void wait(unique_lock<mutex>& __lk);
297    template <class _Predicate>
298        void wait(unique_lock<mutex>& __lk, _Predicate __pred);
299
300    template <class _Clock, class _Duration>
301        cv_status
302        wait_until(unique_lock<mutex>& __lk,
303                   const chrono::time_point<_Clock, _Duration>& __t);
304
305    template <class _Clock, class _Duration, class _Predicate>
306        bool
307        wait_until(unique_lock<mutex>& __lk,
308                   const chrono::time_point<_Clock, _Duration>& __t,
309                   _Predicate __pred);
310
311    template <class _Rep, class _Period>
312        cv_status
313        wait_for(unique_lock<mutex>& __lk,
314                 const chrono::duration<_Rep, _Period>& __d);
315
316    template <class _Rep, class _Period, class _Predicate>
317        bool
318        wait_for(unique_lock<mutex>& __lk,
319                 const chrono::duration<_Rep, _Period>& __d,
320                 _Predicate __pred);
321
322    typedef pthread_cond_t* native_handle_type;
323    _LIBCPP_INLINE_VISIBILITY native_handle_type native_handle() {return &__cv_;}
324
325private:
326    void __do_timed_wait(unique_lock<mutex>& __lk,
327                 chrono::time_point<chrono::system_clock, chrono::nanoseconds>);
328};
329
330template <class _To, class _Rep, class _Period>
331inline _LIBCPP_INLINE_VISIBILITY
332typename enable_if
333<
334    chrono::__is_duration<_To>::value,
335    _To
336>::type
337__ceil(chrono::duration<_Rep, _Period> __d)
338{
339    using namespace chrono;
340    _To __r = duration_cast<_To>(__d);
341    if (__r < __d)
342        ++__r;
343    return __r;
344}
345
346template <class _Predicate>
347void
348condition_variable::wait(unique_lock<mutex>& __lk, _Predicate __pred)
349{
350    while (!__pred())
351        wait(__lk);
352}
353
354template <class _Clock, class _Duration>
355cv_status
356condition_variable::wait_until(unique_lock<mutex>& __lk,
357                               const chrono::time_point<_Clock, _Duration>& __t)
358{
359    using namespace chrono;
360    wait_for(__lk, __t - _Clock::now());
361    return _Clock::now() < __t ? cv_status::no_timeout : cv_status::timeout;
362}
363
364template <class _Clock, class _Duration, class _Predicate>
365bool
366condition_variable::wait_until(unique_lock<mutex>& __lk,
367                   const chrono::time_point<_Clock, _Duration>& __t,
368                   _Predicate __pred)
369{
370    while (!__pred())
371    {
372        if (wait_until(__lk, __t) == cv_status::timeout)
373            return __pred();
374    }
375    return true;
376}
377
378template <class _Rep, class _Period>
379cv_status
380condition_variable::wait_for(unique_lock<mutex>& __lk,
381                             const chrono::duration<_Rep, _Period>& __d)
382{
383    using namespace chrono;
384    if (__d <= __d.zero())
385        return cv_status::timeout;
386    typedef time_point<system_clock, duration<long double, nano> > __sys_tpf;
387    typedef time_point<system_clock, nanoseconds> __sys_tpi;
388    __sys_tpf _Max = __sys_tpi::max();
389    system_clock::time_point __s_now = system_clock::now();
390    steady_clock::time_point __c_now = steady_clock::now();
391    if (_Max - __d > __s_now)
392        __do_timed_wait(__lk, __s_now + __ceil<nanoseconds>(__d));
393    else
394        __do_timed_wait(__lk, __sys_tpi::max());
395    return steady_clock::now() - __c_now < __d ? cv_status::no_timeout :
396                                                 cv_status::timeout;
397}
398
399template <class _Rep, class _Period, class _Predicate>
400inline _LIBCPP_INLINE_VISIBILITY
401bool
402condition_variable::wait_for(unique_lock<mutex>& __lk,
403                             const chrono::duration<_Rep, _Period>& __d,
404                             _Predicate __pred)
405{
406    return wait_until(__lk, chrono::steady_clock::now() + __d,
407                      _VSTD::move(__pred));
408}
409
410_LIBCPP_END_NAMESPACE_STD
411
412#endif  // _LIBCPP___MUTEX_BASE
413