-
Notifications
You must be signed in to change notification settings - Fork 1
/
threadpool.cpp
96 lines (80 loc) · 1.32 KB
/
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
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
89
90
91
92
93
94
95
96
#include "threadpool.h"
ThreadPool::ThreadPool(int taskNum) : m_bRunning(false), m_maxTaskNum(taskNum), m_mutex(), m_notFull(m_mutex), m_notEmpty(m_mutex)
{
}
ThreadPool::~ThreadPool()
{
if (m_bRunning)
{
Stop();
}
}
void ThreadPool::Start(int threadNum)
{
if (m_bRunning)
{
Stop();
}
m_threads.reserve(threadNum);
m_bRunning = true;
for (int i = 0; i < threadNum; ++i)
{
m_threads.emplace_back(new Thread(std::bind(&ThreadPool::RunInThread, this)));
m_threads[i]->Start();
}
}
void ThreadPool::Run(CallFunc func)
{
if (!m_bRunning)
{
func();
}
else
{
LockGuard lock(m_mutex);
while(m_tasks.size() >= m_maxTaskNum)
{
m_notFull.Wait();
}
m_tasks.push_back(func);
m_notEmpty.Notify();
}
}
void ThreadPool::Stop()
{
m_bRunning = false;
m_notEmpty.NotifyAll();
for (std::unique_ptr<Thread> & item : m_threads)
{
item->Join();
}
std::vector<std::unique_ptr<Thread>> temp;
m_threads.swap(temp);
}
ThreadPool::CallFunc ThreadPool::Take()
{
LockGuard lock(m_mutex);
while(m_tasks.empty() && m_bRunning)
{
m_notEmpty.Wait();
}
CallFunc retFunc;
if (m_bRunning)
{
retFunc = m_tasks.front();
m_tasks.pop_front();
m_notFull.Notify();
}
return retFunc;
}
void ThreadPool::RunInThread()
{
while(m_bRunning)
{
CallFunc task = Take();
if (task)
{
task();
}
}
}