forked from organicmaps/organicmaps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwaiter.hpp
79 lines (63 loc) · 1.41 KB
/
waiter.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#pragma once
#include <chrono>
#include <condition_variable>
#include <mutex>
namespace base
{
// Class for multithreaded interruptable waiting.
class Waiter
{
public:
enum class Result
{
PreviouslyNotified,
Timeout,
NoTimeout
};
void Wait()
{
std::unique_lock lock(m_mutex);
if (m_notified)
return;
m_event.wait(lock, [this]() { return m_notified; });
}
template <typename Rep, typename Period>
Result Wait(std::chrono::duration<Rep, Period> const & waitDuration)
{
std::unique_lock lock(m_mutex);
if (m_notified)
return Result::PreviouslyNotified;
auto const result = m_event.wait_for(lock, waitDuration, [this]() { return m_notified; });
return result ? Result::NoTimeout : Result::Timeout;
}
void Notify()
{
SetNotified(true);
m_event.notify_all();
}
void Reset()
{
SetNotified(false);
}
private:
void SetNotified(bool notified)
{
std::lock_guard lock(m_mutex);
m_notified = notified;
}
bool m_notified = false;
std::mutex m_mutex;
std::condition_variable m_event;
};
inline std::string DebugPrint(Waiter::Result result)
{
switch (result)
{
case Waiter::Result::PreviouslyNotified: return "PreviouslyNotified";
case Waiter::Result::NoTimeout: return "NoTimeout";
case Waiter::Result::Timeout: return "Timeout";
default: ASSERT(false, ("Unsupported value"));
}
return {};
}
} // namespace base