-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkerspool.cpp
More file actions
55 lines (41 loc) · 859 Bytes
/
Copy pathworkerspool.cpp
File metadata and controls
55 lines (41 loc) · 859 Bytes
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
/*
* Created on: Feb 22, 2013
* Author: ssobczak
*/
#include "workerspool.h"
#include <thread>
WorkersPool::WorkersPool(int workers) {
std::unique_lock<std::mutex> lock(mutex_);
workers_.resize(workers);
for (int i = 0; i != workers; i++) {
workers_[i] = std::thread(&WorkersPool::do_job, this);
}
running = true;
}
WorkersPool::~WorkersPool() {
stop();
}
void WorkersPool::stop() {
mutex_.lock();
running = false;
cond_.notify_all();
mutex_.unlock();
for (size_t i = 0; i != workers_.size(); i++) {
workers_[i].join();
}
}
void WorkersPool::add_job(const job& job) {
std::unique_lock<std::mutex> lock(mutex_);
job_q_.add(job);
cond_.notify_one();
}
void WorkersPool::do_job() {
std::unique_lock<std::mutex> lock(mutex_);
job job;
while (running) {
cond_.wait(lock);
if (job_q_.pop(&job)) {
job();
}
}
}