Cuberite
A lightweight, fast and extensible game server for Minecraft
Event.cpp
Go to the documentation of this file.
1 
2 // Event.cpp
3 
4 // Interfaces to the cEvent object representing a synchronization primitive that can be waited-for
5 // Implemented using C++11 condition variable and mutex
6 
7 #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
8 
9 #include "Event.h"
10 #include "Errors.h"
11 
12 
13 
14 
16  m_ShouldContinue(false)
17 {
18 }
19 
20 
21 
22 
23 
24 void cEvent::Wait(void)
25 {
26  {
27  std::unique_lock<std::mutex> Lock(m_Mutex);
28  m_CondVar.wait(Lock, [this](){ return m_ShouldContinue; });
29  m_ShouldContinue = false;
30  }
31 }
32 
33 
34 
35 
36 
37 bool cEvent::Wait(unsigned a_TimeoutMSec)
38 {
39  auto dst = std::chrono::system_clock::now() + std::chrono::milliseconds(a_TimeoutMSec);
40  bool Result;
41  {
42  std::unique_lock<std::mutex> Lock(m_Mutex); // We assume that this lock is acquired without much delay - we are the only user of the mutex
43  Result = m_CondVar.wait_until(Lock, dst, [this](){ return m_ShouldContinue; });
44  m_ShouldContinue = false;
45  }
46  return Result;
47 }
48 
49 
50 
51 
52 
53 void cEvent::Set(void)
54 {
55  {
56  std::unique_lock<std::mutex> Lock(m_Mutex);
57  m_ShouldContinue = true;
58  }
59  m_CondVar.notify_one();
60 }
61 
62 
63 
64 
65 
66 void cEvent::SetAll(void)
67 {
68  {
69  std::unique_lock<std::mutex> Lock(m_Mutex);
70  m_ShouldContinue = true;
71  }
72  m_CondVar.notify_all();
73 }
74 
75 
76 
77 
78 
std::condition_variable m_CondVar
The condition variable used as the Event.
Definition: Event.h:47
void Set(void)
Sets the event - releases one thread that has been waiting in Wait().
Definition: Event.cpp:53
std::mutex m_Mutex
Mutex protecting m_ShouldContinue from multithreaded access.
Definition: Event.h:44
bool m_ShouldContinue
Used for checking for spurious wakeups.
Definition: Event.h:41
void Wait(void)
Waits until the event has been set.
Definition: Event.cpp:24
void SetAll(void)
Sets the event - releases all threads that have been waiting in Wait().
Definition: Event.cpp:66
cEvent(void)
Definition: Event.cpp:15