-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathThreadPool.cpp
More file actions
84 lines (73 loc) · 1.49 KB
/
Copy pathThreadPool.cpp
File metadata and controls
84 lines (73 loc) · 1.49 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
84
#include "ThreadPool.h"
namespace sh::core
{
ThreadPool::ThreadPool()
{
}
ThreadPool::~ThreadPool()
{
mu.lock();
bStop = true;
mu.unlock();
cvTask.notify_all();
for (auto& thread : threads)
thread.join();
}
SH_CORE_API void ThreadPool::Init(uint32_t threadNum)
{
for (int i = 0; i < threadNum; ++i)
{
threads.emplace_back([&]
{
while (true)
{
Task task;
{
std::unique_lock<std::mutex> lock{ mu };
cvTask.wait(lock, [this]() {return bStop || !tasks.empty(); });
if (bStop && tasks.empty())
return;
task = std::move(tasks.front());
tasks.pop();
if (!task.bContinous)
++counter;
}
task.fn();
if (!task.bContinous)
{
std::unique_lock<std::mutex> lock{ mu };
--counter;
if (tasks.empty() && counter == 0)
cvDone.notify_all();
}
}
}
);
}
}
SH_CORE_API void ThreadPool::WaitAllTask()
{
std::unique_lock<std::mutex> lock{ mu };
cvDone.wait(lock, [this] {return tasks.empty() && counter == 0; });
}
SH_CORE_API void ThreadPool::Lock()
{
mu.lock();
}
SH_CORE_API void ThreadPool::Unlock()
{
mu.unlock();
}
SH_CORE_API auto ThreadPool::GetThreads() const -> const std::vector<std::thread>&
{
return threads;
}
SH_CORE_API auto ThreadPool::GetThreadNum() const -> uint32_t
{
return threads.size();
}
SH_CORE_API auto ThreadPool::IsInit() const -> bool
{
return threads.size() > 1;
}
}//namepsace