nx_server_plugin_sdk 1.0 Server Plugin SDK

rw_lock.h
1 // Copyright 2018-present Network Optix, Inc. Licensed under MPL 2.0: www.mozilla.org/MPL/2.0/
2
3 #include <condition_variable>
4 #include <mutex>
5
6 namespace rw_lock
7 {
9 class OneWriterManyReaders
10 {
11 public:
12 OneWriterManyReaders()
13 : m_readers(0)
14 {}
15
16 bool tryReadLock()
17 {
18 std::unique_lock<std::mutex> lock(m_mutex); // LOCK
19
20 if (m_readers >= 0)
21 {
22 ++m_readers;
23 return true;
24 }
25 return false;
26 }
27
28 bool tryWriteLock()
29 {
30 std::unique_lock<std::mutex> lock(m_mutex); // LOCK
31
32 if (m_readers == 0)
33 {
34 m_readers = -1;
35 return true;
36 }
37 return false;
38 }
39
40 void writeLock()
41 {
42 std::unique_lock<std::mutex> lock(m_mutex); // LOCK
43
44 if (m_readers != 0)
45 m_cv.wait(lock, [=]{ return m_readers == 0; } );
46
47 m_readers = -1;
48 }
49
50 void unlock()
51 {
52 {
53 std::unique_lock<std::mutex> lock(m_mutex); // LOCK
54
55 if (m_readers > 0)
56 --m_readers;
57 else if (m_readers < 0)
58 ++m_readers;
59 }
60
61 m_cv.notify_one(); // NOTIFY
62 }
63
64 private:
65 std::mutex m_mutex;
66 int32_t m_readers;
67 std::condition_variable m_cv;
68 };
69
70 typedef enum
71 {
72 READ,
73 WRITE,
74 TRY_READ,
75 TRY_WRITE
76 } LockType;
77
79 template<LockType LT>
80 class ScopedLock
81 {
82 public:
83 ScopedLock(OneWriterManyReaders& rw)
84 : m_rw(rw),
85 m_own(false)
86 {
87 acquire();
88 }
89
90 ~ScopedLock()
91 {
92 if (m_own)
93 m_rw.unlock();
94 }
95
96 operator bool () const { return m_own; }
97
98 private:
99 OneWriterManyReaders& m_rw;
100 bool m_own;
101
102 void acquire();
103 };
104
105 template <> inline void ScopedLock<WRITE>::acquire()
106 {
107 m_rw.writeLock();
108 m_own = true;
109 }
110
111 template <> inline void ScopedLock<TRY_READ>::acquire()
112 {
113 m_own = m_rw.tryReadLock();
114 }
115 }
rw_lock::OneWriterManyReaders
Definition: rw_lock.h:9
rw_lock
Definition: rw_lock.h:6
rw_lock::ScopedLock
Definition: rw_lock.h:80