-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreads.cpp
More file actions
78 lines (69 loc) · 1.65 KB
/
Copy pathThreads.cpp
File metadata and controls
78 lines (69 loc) · 1.65 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
#pragma once
#include "Threads.h"
#ifdef _NSTD_THREADS_
_NSTD_BEGIN
thread_pool& thread_pool::spin_up(uint count) {
uint hc = _STD thread::hardware_concurrency();
_Threads.resize(count >= hc ? hc - 1 : count);
_Done = false;
for(_STD thread& t : _Threads)
t = _STD thread([this] { thread_loop(); });
return *this;
}
thread_pool& thread_pool::release() {
{
_STD lock_guard<_STD mutex> lock(_QMutex);
_Done = true;
}
_MutCond.notify_all();
for (_STD thread& t : _Threads)
t.join();
_Threads.clear();
return *this;
}
void thread_pool::thread_loop() {
while (true) {
_Pair_fvp task;
{
_STD unique_lock<_STD mutex> lock(_QMutex);
_MutCond.wait(lock, [this] { return !_Tasks.empty() || _Done; });
if (_Done && _Tasks.empty())
return;
task = _Tasks.front();
_Tasks.pop_front();
}
task.first(task.second);
}
}
void thread_pool::add_task(const _Func& func, void* data) {
{
_STD lock_guard<_STD mutex> lock(_QMutex);
_Tasks.emplace_back(_Pair_fvp(func, data));
}
_MutCond.notify_one();
}
void thread_pool::add_task_inplace(const _Func& _Func, size_t _Index, void* data) {
{
_STD lock_guard<_STD mutex> l(_QMutex);
_Tasks.insert(_Tasks.begin() + _Index, _Pair_fvp(_Func, data));
}
_MutCond.notify_one();
}
void thread_pool::add_task(_Pair_fvp& pair) {
{
_STD lock_guard<_STD mutex> lock(_QMutex);
_Tasks.emplace_back(pair);
}
_MutCond.notify_one();
}
void thread_pool::add_task(_STD vector<_Pair_fvp> task_list) {
{
_STD lock_guard<_STD mutex> lock(_QMutex);
for (_Pair_fvp& task : task_list)
_Tasks.push_back(task);
}
_NSTD_FOR_I(task_list.size())
_MutCond.notify_one();
}
_NSTD_END
#endif // _NSTD_THREADS_