-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathTaskBuffer.cpp
52 lines (45 loc) · 1 KB
/
TaskBuffer.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
#include "TaskBuffer.hpp"
#include <cstdlib>
#include <stdexcept>
TaskBuffer::TaskBuffer() {
#ifdef USE_LIBUV
async_hdl = (uv_async_t *)std::malloc(sizeof(uv_async_t));
if (async_hdl == nullptr) {
throw std::bad_alloc();
}
uv_async_init(uv_default_loop(), async_hdl, (uv_async_cb)&asyncExecute);
async_hdl->data = this;
#endif
}
TaskBuffer::~TaskBuffer() {
/* Should I run remaining tasks? */
#ifdef USE_LIBUV
uv_close((uv_handle_t *)async_hdl, (uv_close_cb)([](uv_handle_t * const hdl){
std::free(hdl);
}));
#endif
}
void TaskBuffer::runTasks() {
#ifdef USE_LIBUV
uv_async_send(async_hdl);
#else
executeTasks();
#endif
}
#ifdef USE_LIBUV
void TaskBuffer::asyncExecute(uv_async_t * const hdl) {
TaskBuffer * const tb = (TaskBuffer *)hdl->data;
tb->executeTasks();
}
#endif
void TaskBuffer::queueTask(const std::function<void(void)> & task) {
buflock.lock();
taskbuf.push_back(task);
buflock.unlock();
}
void TaskBuffer::executeTasks() {
for (auto & task : taskbuf) {
task();
}
taskbuf.clear();
}