-
Notifications
You must be signed in to change notification settings - Fork 23
/
backgroundworker.cpp
139 lines (110 loc) · 2.87 KB
/
backgroundworker.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include <string.h>
#include <unistd.h>
#include <poll.h>
#include "backgroundworker.h"
#include "logger.h"
void BackgroundWorker::doWork()
{
struct pollfd fds[1];
memset(fds, 0, sizeof(struct pollfd));
fds[0].fd = wakeup_fd;
fds[0].events = POLLIN;
while (running)
{
executing_task = false;
int fd_count = poll(fds, 1, 1000);
if (fd_count == 0)
continue;
if (fd_count < 0)
{
Logger::getInstance()->log(LOG_ERR) << "poll() error in BackgroundWorker: " << strerror(errno);
continue;
}
if (fds[0].revents & POLLIN)
{
uint64_t _;
if (read(fds[0].fd, &_, sizeof(uint64_t)) < 0)
{
Logger::getInstance()->log(LOG_ERR) << "Error while reading from wakeup_fd: " << strerror(errno);
}
}
if (!running)
continue;
std::list<std::function<void()>> copied_tasks;
{
std::lock_guard<std::mutex> locker(task_mutex);
copied_tasks = std::move(this->tasks);
this->tasks.clear();
}
for(auto &f : copied_tasks)
{
executing_task = true;
try
{
f();
}
catch (std::exception &ex)
{
Logger *logger = Logger::getInstance();
logger->log(LOG_ERR) << "Error in BackgroundWorker::do_work: " << ex.what();
}
}
}
}
void BackgroundWorker::wake_up_thread()
{
uint64_t one = 1;
if (write(wakeup_fd, &one, sizeof(uint64_t)) < 0)
{
Logger::getInstance()->log(LOG_ERR) << "BackgroundWorker::wake_up_thread: " << strerror(errno);
}
}
BackgroundWorker::BackgroundWorker()
{
wakeup_fd = eventfd(0, EFD_NONBLOCK);
if (wakeup_fd < 0)
{
throw std::runtime_error("Failed to initialize eventfd in background worker: " + std::string(strerror(errno)));
}
}
BackgroundWorker::~BackgroundWorker()
{
this->stop();
if (t.joinable())
t.join();
if (wakeup_fd >= 0)
{
close(wakeup_fd);
wakeup_fd = -1;
}
}
void BackgroundWorker::start()
{
std::lock_guard<std::mutex> locker(task_mutex);
if (t.joinable())
return;
auto f = std::bind(&BackgroundWorker::doWork, this);
t = std::thread(f);
pthread_t native = this->t.native_handle();
pthread_setname_np(native, "BgTasks");
}
void BackgroundWorker::stop()
{
this->running = false;
this->wake_up_thread();
}
void BackgroundWorker::waitForStop()
{
if (t.joinable())
t.join();
}
void BackgroundWorker::addTask(std::function<void ()> f, bool only_if_idle)
{
if (only_if_idle && executing_task)
return;
{
std::lock_guard<std::mutex> locker(task_mutex);
this->tasks.push_front(f);
}
wake_up_thread();
}