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 //===----------------------------------------------------------------------===//
10 #define _LIBCPP_BUILDING_SHARED_MUTEX
11 #include "shared_mutex"
13 _LIBCPP_BEGIN_NAMESPACE_STD
15 shared_mutex::shared_mutex()
20 // Exclusive ownership
25 unique_lock
<mutex
> lk(__mut_
);
26 while (__state_
& __write_entered_
)
28 __state_
|= __write_entered_
;
29 while (__state_
& __n_readers_
)
34 shared_mutex::try_lock()
36 unique_lock
<mutex
> lk(__mut_
);
39 __state_
= __write_entered_
;
46 shared_mutex::unlock()
48 lock_guard
<mutex
> _(__mut_
);
50 __gate1_
.notify_all();
56 shared_mutex::lock_shared()
58 unique_lock
<mutex
> lk(__mut_
);
59 while ((__state_
& __write_entered_
) || (__state_
& __n_readers_
) == __n_readers_
)
61 unsigned num_readers
= (__state_
& __n_readers_
) + 1;
62 __state_
&= ~__n_readers_
;
63 __state_
|= num_readers
;
67 shared_mutex::try_lock_shared()
69 unique_lock
<mutex
> lk(__mut_
);
70 unsigned num_readers
= __state_
& __n_readers_
;
71 if (!(__state_
& __write_entered_
) && num_readers
!= __n_readers_
)
74 __state_
&= ~__n_readers_
;
75 __state_
|= num_readers
;
82 shared_mutex::unlock_shared()
84 lock_guard
<mutex
> _(__mut_
);
85 unsigned num_readers
= (__state_
& __n_readers_
) - 1;
86 __state_
&= ~__n_readers_
;
87 __state_
|= num_readers
;
88 if (__state_
& __write_entered_
)
91 __gate2_
.notify_one();
95 if (num_readers
== __n_readers_
- 1)
96 __gate1_
.notify_one();
101 _LIBCPP_END_NAMESPACE_STD