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 
11 
12 
13 
15  m_ShouldContinue(false)
16 {
17 }
18 
19 
20 
21 
22 
23 void cEvent::Wait(void)
24 {
25  {
26  std::unique_lock<std::mutex> Lock(m_Mutex);
27  m_CondVar.wait(Lock, [this](){ return m_ShouldContinue; });
28  m_ShouldContinue = false;
29  }
30 }
31 
32 
33 
34 
35 
36 bool cEvent::Wait(unsigned a_TimeoutMSec)
37 {
38  auto dst = std::chrono::system_clock::now() + std::chrono::milliseconds(a_TimeoutMSec);
39  bool Result;
40  {
41  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
42  Result = m_CondVar.wait_until(Lock, dst, [this](){ return m_ShouldContinue; });
43  m_ShouldContinue = false;
44  }
45  return Result;
46 }
47 
48 
49 
50 
51 
52 void cEvent::Set(void)
53 {
54  {
55  std::unique_lock<std::mutex> Lock(m_Mutex);
56  m_ShouldContinue = true;
57  }
58  m_CondVar.notify_one();
59 }
60 
61 
62 
63 
64 
65 void cEvent::SetAll(void)
66 {
67  {
68  std::unique_lock<std::mutex> Lock(m_Mutex);
69  m_ShouldContinue = true;
70  }
71  m_CondVar.notify_all();
72 }
73 
74 
75 
76 
77 
void Wait(void)
Waits until the event has been set.
Definition: Event.cpp:23
bool m_ShouldContinue
Used for checking for spurious wakeups.
Definition: Event.h:41
std::mutex m_Mutex
Mutex protecting m_ShouldContinue from multithreaded access.
Definition: Event.h:44
void SetAll(void)
Sets the event - releases all threads that have been waiting in Wait().
Definition: Event.cpp:65
cEvent(void)
Definition: Event.cpp:14
void Set(void)
Sets the event - releases one thread that has been waiting in Wait().
Definition: Event.cpp:52
std::condition_variable m_CondVar
The condition variable used as the Event.
Definition: Event.h:47