-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTPool.cpp
More file actions
83 lines (73 loc) · 1.78 KB
/
TPool.cpp
File metadata and controls
83 lines (73 loc) · 1.78 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
#include <iostream>
#include <chrono>
#include <thread>
#include <exception>
#include "TPool.hpp"
int TQueue::pop(std::function<void()> &task) {
std::unique_lock<std::mutex> safe(_lock);
if (!_queue.empty()) {
task = _queue.back();
_queue.pop_back();
return (0);
}
return (-1);
}
int TQueue::push(std::function<void()> &task) {
std::unique_lock<std::mutex> safe(_lock);
_queue.emplace_front(std::move(task));
return (0);
}
size_t TQueue::size() const {
std::unique_lock<std::mutex> safe(_lock);
return (_queue.size());
}
void TPool::destroy() {
_end = true;
_cnd.notify_all();
for (unsigned int i = 0; i < _max; ++i)
if (_workers[i].joinable())
_workers[i].join();
}
int TPool::addTask(std::function<void()> &task) {
int ret = 0;
{
std::unique_lock<std::mutex> safe(_lock);
ret = _queue.push(task);
}
if (!ret) {
_cnd.notify_one();
return (0);
}
return (1);
}
const unsigned int &TPool::threadsWorking() const {
std::unique_lock<std::mutex> safe(_lock);
return (_workingOn);
}
bool TPool::isBusy() const {
return (_queue.size() > 0 || threadsWorking() > 0);
}
void TPool::infWorker() {
std::function<void()> task = nullptr;
while (!_end) {
{
std::unique_lock<std::mutex> safe(_lock);
if (!_queue.size()) {
std::this_thread::yield();
_cnd.wait(safe);
}
if (_end && !_queue.size())
return;
_queue.pop(task);
_workingOn++;
}
if (task) {
task();
task = nullptr;
}
{
std::unique_lock<std::mutex> safe(_lock);
_workingOn--;
}
}
}