-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththread.cpp
89 lines (72 loc) · 1.43 KB
/
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include "thread.h"
#include <iostream>
Thread::Thread() :isRunning(false)
{
thread.reset(new std::thread([this]
{
isRunning = true;
this->start();
}));
}
Thread::~Thread()
{
stop();
}
void Thread::start()
{
std::unique_lock<std::mutex> lock(mutex);
do {
while (isRunning && tasks.empty())
itemInQueue.wait(lock);
while (!tasks.empty())
{
auto size = tasks.size();
std::cout << "Number of pending tasks are " << size << std::endl;
const std::function<void()> t = tasks.front();
tasks.pop_front();
lock.unlock();
t();
lock.lock();
}
itemInQueue.notify_all();
} while (isRunning);
itemInQueue.notify_all();
}
void Thread::doAsync(const std::function<void()>& t)
{
std::lock_guard<std::mutex> _(mutex);
tasks.push_back(t);
itemInQueue.notify_one();
}
void Thread::doSync(const std::function<void()>& t)
{
std::condition_variable event;
bool finished = false;
std::unique_lock<std::mutex> lock(mutex);
auto lambda = [this, &t, &finished, &event]
{
t();
std::lock_guard<std::mutex> lock(mutex);
finished = true;
event.notify_one();
};
tasks.push_back(lambda);
itemInQueue.notify_one();
while (!finished)
event.wait(lock);
}
void Thread::wait()
{
std::unique_lock<std::mutex> lock(mutex);
while (!tasks.empty())
itemInQueue.wait(lock);
}
void Thread::stop()
{
{
std::lock_guard<std::mutex> lock(mutex);
isRunning = false;
itemInQueue.notify_one();
}
thread->join();
}