-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmostlyharmless_TaskThread.cpp
More file actions
71 lines (57 loc) · 1.81 KB
/
mostlyharmless_TaskThread.cpp
File metadata and controls
71 lines (57 loc) · 1.81 KB
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
//
// Created by Syl on 12/08/2024.
//
#include "mostly_harmless/utils/mostlyharmless_OnScopeExit.h"
#include <mostly_harmless/utils/mostlyharmless_TaskThread.h>
#include <cassert>
#include <thread>
namespace mostly_harmless::utils {
TaskThread::~TaskThread() noexcept {
stop();
}
auto TaskThread::perform() -> void {
auto expected{ false };
if (m_isThreadRunning.compare_exchange_strong(expected, true)) {
auto actionWrapper = [this]() -> void {
OnScopeExit se{ [this]() -> void {
m_isThreadRunning.store(false);
} };
action();
};
m_thread = std::make_unique<std::thread>(std::move(actionWrapper));
}
}
auto TaskThread::stop() noexcept -> void {
signalStop();
if (!m_thread) {
return;
}
if (m_thread->joinable()) {
m_thread->join();
}
reset();
}
auto TaskThread::sleep() -> void {
m_sleepState.canWakeUp = false;
std::unique_lock<std::mutex> ul{ m_sleepState.mutex };
m_sleepState.conditionVariable.wait(ul, [this]() -> bool { return m_sleepState.canWakeUp; });
}
auto TaskThread::wake() -> void {
m_sleepState.canWakeUp = true;
std::lock_guard<std::mutex> lock{ m_sleepState.mutex };
m_sleepState.conditionVariable.notify_one();
}
auto TaskThread::isThreadRunning() const noexcept -> bool {
return m_isThreadRunning;
}
auto TaskThread::signalStop() -> void {
m_stop.store(true);
}
auto TaskThread::hasSignalledStop() const noexcept -> bool {
return m_stop;
}
auto TaskThread::reset() -> void {
m_thread.reset();
m_stop = false;
}
} // namespace mostly_harmless::utils