-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththreadpool.hpp
73 lines (57 loc) · 1.51 KB
/
threadpool.hpp
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
#ifndef DBSTD_THREADPOOL
#define DBSTD_THREADPOOL
#include "ringbuffer.hpp"
#include <thread>
#include <functional>
namespace dbstd {
// Single Producer ThreadPool
class SP_ThreadPool {
private:
RingBuffer<std::function<void()>> jobQueue;
int numThreads;
std::vector<std::thread> threads;
std::mutex mut;
std::atomic<bool> keepGoing;
void threadRunner() {
while (keepGoing) {
std::optional<std::function<void()>> job;
{
std::scoped_lock lock(mut);
job = jobQueue.dequeue_and_get();
}
if (job) (*job)();
}
}
public:
SP_ThreadPool(size_t minQueueCapacity, int numThreads)
: jobQueue(minQueueCapacity)
, numThreads(numThreads)
, threads()
, keepGoing(true)
{}
~SP_ThreadPool() {
stop();
}
SP_ThreadPool(const SP_ThreadPool&) = delete;
SP_ThreadPool(SP_ThreadPool&&) = delete;
SP_ThreadPool& operator=(const SP_ThreadPool&&) = delete;
SP_ThreadPool& operator=(SP_ThreadPool&&) = delete;
void start() {
threads.reserve(numThreads);
for (int i = 0; i < numThreads; ++i) {
threads.emplace_back(&SP_ThreadPool::threadRunner, this);
}
}
void stop() {
keepGoing = false;
for (auto& thread : threads) {
thread.join();
}
}
void enqueueJob(std::function<void()>&& job) {
std::scoped_lock lock(mut);
jobQueue.enqueue(std::move(job));
}
};
}
#endif