ECSTASY
All in the name
Loading...
Searching...
No Matches
SharedRecursiveMutex.cpp
Go to the documentation of this file.
1
11
13
14namespace ecstasy::thread
15{
17 {
19
20 if (_owner == this_id) {
21 // recursive locking
23 } else {
24 // Unlock the shared lock if any
25 if (get_shared_lock_count() > 0) {
27 // Add a count to avoid the unlock_shared() to be called before the unlock()
28 // While the thread has exclusive lock, there is no real shared_lock, therefore calling unlock_shared()
29 // would cause an error
30 ++_shared_locks[this_id];
31 }
32 // normal locking
34 _owner = this_id;
35 _lock_count = 1;
36 }
37 }
38
40 {
42 // Increment the shared lock count for this thread
43 int &shared_lock_count = ++_shared_locks[this_id];
44
45 // If it is the first shared lock, the count is set to 1 by incrementing the 0 default initialized value
46 if (shared_lock_count == 1) {
47 if (_owner != this_id)
49 else
50 ++shared_lock_count;
51 }
52 }
53
55 {
56 if (_lock_count > 1) {
57 // recursive unlocking
59 } else {
60 // normal unlocking
62 _lock_count = 0;
64 // Apply the remaining shared locks that were made before/inside the exclusive lock
65 if (get_shared_lock_count() > 0) {
66 // Remove the count added in lock() and call remaininc lock_shared()
69 }
70 }
71 }
72
74 {
75 int &_shared_lock_count = --_shared_locks.at(std::this_thread::get_id());
76
77 // If it was the last shared lock, unlock the shared mutex
78 if (_shared_lock_count == 0)
80 }
81
83 {
84 // Better than handling exceptions
85 if (has_shared_lock())
86 return _shared_locks.at(std::this_thread::get_id());
87 else
88 return 0;
89 }
90
91 bool SharedRecursiveMutex::has_shared_lock(void) const noexcept
92 {
93 return const_cast<const std::unordered_map<std::thread::id, int> &>(_shared_locks)
95 != _shared_locks.cend();
96 }
97
98} // namespace ecstasy::thread
Wrapper for std::shared_mutex allowing recursive locking by the same thread.
T at(T... args)
void unlock()
Unlock the mutex locked with exclusive access.
std::shared_mutex _shared_mutex
Internal shared mutex.
std::unordered_map< std::thread::id, int > _shared_locks
Shared lock count.
void lock_shared() const
Lock the mutex with shared access.
void lock()
Lock the mutex with exclusive access.
std::atomic< std::thread::id > _owner
Owner of the mutex.
void unlock_shared() const
Unlock the mutex locked with shared access.
int get_shared_lock_count(void) const noexcept
Get the number of recursive shared locks held by the current thread.
T get_id(T... args)
T lock(T... args)
T lock_shared(T... args)
Namespace regrouping the thread safe ecstasy symbols.
Definition include.hpp:26
T unlock(T... args)
T unlock_shared(T... args)