-
Notifications
You must be signed in to change notification settings - Fork 2
/
delay_thread.cpp
69 lines (65 loc) · 1.75 KB
/
delay_thread.cpp
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
#include "delay_thread.hpp"
#include "blockingconcurrentqueue.h"
#include <chrono>
#include <functional>
#include <thread>
using namespace std;
using namespace chrono;
namespace mutils {
namespace delay_thread {
class delay_thread {
private:
struct delayed_action {
function<void()> task;
high_resolution_clock::time_point time;
};
nanoseconds delay_amount;
moodycamel::BlockingConcurrentQueue<delayed_action> q;
std::atomic<bool> destroying{false};
thread t{[this] {
auto& q = this->q;
delayed_action action;
while(bool success = q.wait_dequeue_timed(action, 1s)) {
if(destroying)
break;
else {
while(high_resolution_clock::now() < action.time) {
if(destroying)
break;
this_thread::sleep_for(1ms);
}
if(destroying)
break;
action.task();
}
}
}};
delay_thread() = default;
~delay_thread() {
destroying = true;
t.join();
}
public:
template <typename T>
void set_delay(T&& t) {
delay_amount = t;
}
void submit_action(std::function<void()> task) {
q.enqueue(delayed_action{task, high_resolution_clock::now() + delay_amount});
}
static delay_thread& instance() {
static delay_thread ret;
return ret;
}
};
void set_delay(std::chrono::seconds t) {
delay_thread::instance().set_delay(t);
}
void set_delay_highres(std::chrono::nanoseconds t) {
delay_thread::instance().set_delay(t);
}
void delay_action(std::function<void()> a) {
delay_thread::instance().submit_action(a);
}
} // namespace delay_thread
} // namespace mutils