-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.cpp
More file actions
76 lines (63 loc) · 1.66 KB
/
ThreadPool.cpp
File metadata and controls
76 lines (63 loc) · 1.66 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
#include "ThreadPool.h"
ThreadPool::ThreadPool(int t)
{
if( t <= 0 )
t = 1;
ending = false;
for(int i = 0; i < t; i++)
threads.push_back( std::thread(&ThreadPool::WorkLoop, this) );
}
ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queuemutex);
ending = true;
}
//wake up all threads
workqueuecondvar.notify_all();
for( auto& thread : threads )
{
if( thread.joinable() )
thread.join();
}
}
std::map<std::thread::id, std::vector<std::string> > ThreadPool::GetLogs()
{
for( auto& thread : threads )
{
if( filelogs.find(thread.get_id()) == filelogs.end() )
filelogs[thread.get_id()].push_back("");
}
return filelogs;
}
void ThreadPool::AddWork(const std::function<void()>& work, std::string filename)
{
std::unique_lock<std::mutex> lock(queuemutex);
workqueue.push( make_pair(work, filename) );
workqueuecondvar.notify_one();
}
void ThreadPool::WorkLoop()
{
while( true )
{
std::function<void()> work;
{
std::unique_lock<std::mutex> lock(queuemutex);
workqueuecondvar.wait( lock, [&] { return !workqueue.empty() || ending; });
if( ending ) break;
work = workqueue.front().first;
std::string workfilename = workqueue.front().second;
workqueue.pop();
filelogs[ std::this_thread::get_id() ].push_back(workfilename);
}
work();
}
}
bool ThreadPool::Busy() {
bool poolbusy;
{
std::unique_lock<std::mutex> lock(queuemutex);
poolbusy = !workqueue.empty();
}
return poolbusy;
}