forked from projectM-visualizer/projectm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BackgroundWorker.h
72 lines (62 loc) · 1.66 KB
/
BackgroundWorker.h
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
#pragma once
#include <condition_variable>
#include <mutex>
/**
* Small class to encapsulate synchronization of a simple background task runner
*/
class BackgroundWorkerSync
{
public:
BackgroundWorkerSync() = default;
void Reset()
{
m_isWorkToDo = false;
m_finished = false;
}
// called by foreground
void WakeUpBackgroundTask()
{
std::lock_guard<std::mutex> guard(m_mutex);
m_isWorkToDo = true;
m_conditionStartWork.notify_one();
}
// called by foreground
void WaitForBackgroundTaskToFinish()
{
std::unique_lock<std::mutex> guard(m_mutex);
while (m_isWorkToDo)
{
m_conditionWorkDone.wait(guard);
}
}
// called by foreground() when shutting down, background thread should exit
void FinishUp()
{
std::lock_guard<std::mutex> guard(m_mutex);
m_finished = true;
m_conditionStartWork.notify_all();
}
// called by background
auto WaitForWork() -> bool
{
std::unique_lock<std::mutex> guard(m_mutex);
while (!m_isWorkToDo && !m_finished)
{
m_conditionStartWork.wait(guard);
}
return !m_finished;
}
// called by background
void FinishedWork()
{
std::lock_guard<std::mutex> guard(m_mutex);
m_isWorkToDo = false;
m_conditionWorkDone.notify_one();
}
private:
mutable std::mutex m_mutex; //!< Mutex that controls access to the work flags.
std::condition_variable m_conditionStartWork;
std::condition_variable m_conditionWorkDone;
volatile bool m_isWorkToDo{ false };
volatile bool m_finished{ false };
};