1 //===---------------------- shared_mutex.cpp ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 #ifndef _LIBCPP_HAS_NO_THREADS
13 #define _LIBCPP_BUILDING_SHARED_MUTEX
14 #include "shared_mutex"
16 _LIBCPP_BEGIN_NAMESPACE_STD
18 shared_timed_mutex::shared_timed_mutex()
23 // Exclusive ownership
26 shared_timed_mutex::lock()
28 unique_lock<mutex> lk(__mut_);
29 while (__state_ & __write_entered_)
31 __state_ |= __write_entered_;
32 while (__state_ & __n_readers_)
37 shared_timed_mutex::try_lock()
39 unique_lock<mutex> lk(__mut_);
42 __state_ = __write_entered_;
49 shared_timed_mutex::unlock()
51 lock_guard<mutex> _(__mut_);
53 __gate1_.notify_all();
59 shared_timed_mutex::lock_shared()
61 unique_lock<mutex> lk(__mut_);
62 while ((__state_ & __write_entered_) || (__state_ & __n_readers_) == __n_readers_)
64 unsigned num_readers = (__state_ & __n_readers_) + 1;
65 __state_ &= ~__n_readers_;
66 __state_ |= num_readers;
70 shared_timed_mutex::try_lock_shared()
72 unique_lock<mutex> lk(__mut_);
73 unsigned num_readers = __state_ & __n_readers_;
74 if (!(__state_ & __write_entered_) && num_readers != __n_readers_)
77 __state_ &= ~__n_readers_;
78 __state_ |= num_readers;
85 shared_timed_mutex::unlock_shared()
87 lock_guard<mutex> _(__mut_);
88 unsigned num_readers = (__state_ & __n_readers_) - 1;
89 __state_ &= ~__n_readers_;
90 __state_ |= num_readers;
91 if (__state_ & __write_entered_)
94 __gate2_.notify_one();
98 if (num_readers == __n_readers_ - 1)
99 __gate1_.notify_one();
104 _LIBCPP_END_NAMESPACE_STD
106 #endif // !_LIBCPP_HAS_NO_THREADS