Fixes #19. Add destructor to ConditionBank.
[junction.git] / junction / striped / AutoResetEvent.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_AUTORESETEVENT_H
14 #define JUNCTION_STRIPED_AUTORESETEVENT_H
15
16 #include <junction/Core.h>
17 #include <junction/striped/ConditionBank.h>
18
19 namespace junction {
20 namespace striped {
21
22 class AutoResetEvent {
23 private:
24     JUNCTION_STRIPED_CONDITIONBANK_DEFINE_MEMBER()
25     bool m_status;
26
27 public:
28     AutoResetEvent(bool status) : m_status(status) {
29     }
30
31     void wait() {
32         ConditionPair& pair = JUNCTION_STRIPED_CONDITIONBANK_GET(this);
33         turf::LockGuard<turf::Mutex> guard(pair.mutex);
34         while (!m_status)
35             pair.condVar.wait(guard);
36         m_status = false;
37     }
38
39     void signal() {
40         ConditionPair& pair = JUNCTION_STRIPED_CONDITIONBANK_GET(this);
41         turf::LockGuard<turf::Mutex> guard(pair.mutex);
42         if (!m_status) {
43             m_status = true;
44             // FIXME: Is there a more efficient striped::Mutex implementation that is safe from deadlock?
45             // This approach will wake up too many threads when there is heavy contention.
46             // However, if we don't wakeAll(), we will miss wakeups, since ConditionPairs are shared.
47             pair.condVar.wakeAll();
48         }
49     }
50 };
51
52 } // namespace striped
53 } // namespace junction
54
55 #endif // JUNCTION_STRIPED_AUTORESETEVENT_H