-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThread.h
More file actions
118 lines (107 loc) · 2.67 KB
/
Copy pathThread.h
File metadata and controls
118 lines (107 loc) · 2.67 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#ifndef SLIMEFINDER_THREAD_H
#define SLIMEFINDER_THREAD_H
#include <queue>
#include <mutex>
#include <thread>
#include <functional>
#include <condition_variable>
#include <atomic>
#include <iostream>
#include <vector>
template<typename T>
class ThreadSafeResults {
std::priority_queue<T> results_;
std::mutex mutex_{};
public:
void addResult(const T &res)
{
std::lock_guard<std::mutex> lock(mutex_);
results_.emplace(res);
}
void addResults(const std::vector<T> &newResults)
{
std::lock_guard<std::mutex> lock(mutex_);
for (const auto &result: newResults)
{
results_.emplace(result);
}
}
const T &get() const
{
return results_.top();
}
bool empty() const
{
return results_.empty();
}
std::vector<T> getAllResults()
{
std::lock_guard<std::mutex> lock(mutex_);
std::vector<T> allResults;
while (!results_.empty())
{
allResults.push_back(results_.top());
results_.pop();
}
return allResults;
}
void clear()
{
std::lock_guard<std::mutex> lock(mutex_);
results_ = decltype(results_){};
}
};
class ThreadPool {
private:
std::vector<std::thread> workers;
std::queue<std::function<void()> > tasks;
std::mutex queueMutex;
std::condition_variable condition;
std::atomic<bool> stop{false};
public:
explicit ThreadPool(size_t threads)
{
for (size_t i = 0; i < threads; ++i)
{
workers.emplace_back([this] {
while (true)
{
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queueMutex);
this->condition.wait(lock, [this] {
return this->stop || !this->tasks.empty();
});
if (this->stop && this->tasks.empty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
});
}
}
template<class F>
void enqueue(F &&f)
{
{
std::unique_lock<std::mutex> lock(queueMutex);
tasks.emplace(std::forward<F>(f));
}
condition.notify_one();
}
~ThreadPool()
{
stop = true;
condition.notify_all();
for (std::thread &worker: workers)
{
if (worker.joinable())
{
worker.join();
}
}
}
};
#endif