Fixes #19. Add destructor to ConditionBank.
[junction.git] / junction / striped / Mutex.h
1 /*------------------------------------------------------------------------
2   Junction: Concurrent data structures in C++
3   Copyright (c) 2016 Jeff Preshing
4
5   Distributed under the Simplified BSD License.
6   Original location: https://github.com/preshing/junction
7
8   This software is distributed WITHOUT ANY WARRANTY; without even the
9   implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10   See the LICENSE file for more information.
11 ------------------------------------------------------------------------*/
12
13 #ifndef JUNCTION_STRIPED_MUTEX_H
14 #define JUNCTION_STRIPED_MUTEX_H
15
16 #include <junction/Core.h>
17
18 #if JUNCTION_USE_STRIPING
19
20 //-----------------------------------
21 // Striping enabled
22 //-----------------------------------
23 #include <junction/striped/AutoResetEvent.h>
24
25 namespace junction {
26 namespace striped {
27
28 // Not recursive
29 class Mutex {
30 private:
31     turf::Atomic<sreg> m_status;
32     junction::striped::AutoResetEvent m_event;
33
34     void lockSlow() {
35         while (m_status.exchange(1, turf::Acquire) >= 0)
36             m_event.wait();
37     }
38
39 public:
40     Mutex() : m_status(-1), m_event(false) {
41     }
42
43     void lock() {
44         if (m_status.exchange(0, turf::Acquire) >= 0)
45             lockSlow();
46     }
47
48     bool tryLock() {
49         return (m_status.compareExchange(-1, 0, turf::Acquire) < 0);
50     }
51
52     void unlock() {
53         if (m_status.exchange(-1, turf::Release) > 0)
54             m_event.signal();
55     }
56 };
57
58 } // namespace striped
59 } // namespace junction
60
61 #else // JUNCTION_USE_STRIPING
62
63 //-----------------------------------
64 // Striping disabled
65 //-----------------------------------
66 #include <turf/Mutex.h>
67
68 namespace junction {
69 namespace striped {
70 typedef turf::Mutex Mutex;
71 } // namespace striped
72 } // namespace junction
73
74 #endif // JUNCTION_USE_STRIPING
75
76 #endif // JUNCTION_STRIPED_MUTEX_H