-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorkerPool.cc
More file actions
83 lines (74 loc) · 2.3 KB
/
WorkerPool.cc
File metadata and controls
83 lines (74 loc) · 2.3 KB
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
#include <vector>
#include "WorkerPool.h"
WorkerPool::WorkerPool(const AppCallback& callback, uint32_t pool_size):
callback_(callback), finished_(false) {
for (uint32_t i = 0; i < pool_size; ++i) {
threads_.emplace_back(&WorkerPool::DoWork, this);
}
}
WorkerPool::~WorkerPool() {
{ // Lock scope
std::unique_lock<std::mutex> lock(mutex_);
finished_ = true;
}
cond_.notify_all();
for (std::thread& thread: threads_) {
thread.join();
}
}
// Producer thread context
void WorkerPool::Add(WorkItemPtr work_item) {
{ // Lock scope
std::unique_lock<std::mutex> lock(mutex_);
queue_.emplace(work_item);
}
cond_.notify_all();
}
// Consumer threads context
void WorkerPool::DoWork() {
while (true) {
WorkItemPtr work_item;
{ // Lock scope
std::unique_lock<std::mutex> lock(mutex_);
cond_.wait(lock, [this] () {
return !queue_.empty() || finished_;
});
if (!queue_.empty()) {
work_item = std::move(queue_.front());
queue_.pop();
} else if (finished_) {
break;
}
}
if (work_item) {
work_item->Process();
callback_(work_item);
}
}
}
void ReadyForDelivery(WorkItemPtr work_item) {
std::shared_ptr<SleepyWorkItem> sleepy_work_item =
std::dynamic_pointer_cast<SleepyWorkItem> (work_item);
std::cout << "Id " << sleepy_work_item->id() << ", " <<
sleepy_work_item->msec_duration() <<
" millisec is ready for delivery!" << std::endl;
}
int main(int argc, char** argv) {
std::vector<WorkItemPtr> items;
items.emplace_back(std::make_shared<SleepyWorkItem>(1, 100));
items.emplace_back(std::make_shared<SleepyWorkItem>(2, 700));
items.emplace_back(std::make_shared<SleepyWorkItem>(3, 500));
items.emplace_back(std::make_shared<SleepyWorkItem>(4, 200));
items.emplace_back(std::make_shared<SleepyWorkItem>(5, 300));
auto start = std::chrono::high_resolution_clock::now();
{ // Object scope
WorkerPool worker_pool(std::bind(&ReadyForDelivery, std::placeholders::_1), 4);
for (WorkItemPtr item: items) {
worker_pool.Add(item);
}
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "Completed work items in " <<
std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " milliseconds." << std::endl;
return 0;
}