forked from halfgaar/FlashMQ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backgroundworker.cpp
86 lines (68 loc) · 1.68 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
#include "backgroundworker.h"
#include "logger.h"
void BackgroundWorker::doWork()
{
while (running)
{
// TODO: semaphore/event/poll
std::this_thread::sleep_for(std::chrono::milliseconds(10));
if (!running)
continue;
{
std::lock_guard<std::mutex> locker(task_mutex);
if (this->tasks.empty())
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)
{
try
{
f();
}
catch (std::exception &ex)
{
Logger *logger = Logger::getInstance();
logger->log(LOG_ERR) << "Error in BackgroundWorker::do_work: " << ex.what();
}
}
}
}
BackgroundWorker::BackgroundWorker()
{
}
BackgroundWorker::~BackgroundWorker()
{
this->running = false;
if (t.joinable())
t.join();
}
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;
}
void BackgroundWorker::waitForStop()
{
if (t.joinable())
t.join();
}
void BackgroundWorker::addTask(std::function<void ()> f)
{
std::lock_guard<std::mutex> locker(task_mutex);
this->tasks.push_front(f);
}