-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththreadPool.cpp
40 lines (37 loc) · 914 Bytes
/
threadPool.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
#include "threadPool.h"
threadPool::threadPool(int threadNum)
{
this->threadNum=threadNum;
for (int i=0;i<threadNum;i++)
threads.push_back(threadLoop(i));
}
std::thread* threadPool::threadLoop(int num)
{
return new std::thread([&,num](){
//signal(SIGPIPE , SIG_IGN);
while (!terminate)
{
std::unique_lock<std::mutex> lck(mutex);
if (queue.empty()) {
consumer.wait(lck);
}
bool result;
std::function<void()> f;
result=queue.pop(f);
if (result) {
f();
}
}
});
}
threadPool::~threadPool()
{
terminate=true;
consumer.notify_all();
std::this_thread::sleep_for(std::chrono::microseconds(100));
consumer.notify_all();
for (auto *thread:threads) {
if (thread->joinable())
thread->join();
}
}