-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDispatchPool.hpp
More file actions
80 lines (71 loc) · 2.31 KB
/
DispatchPool.hpp
File metadata and controls
80 lines (71 loc) · 2.31 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
/**
* @file DispatchPool.hpp
* @brief Fixed-size thread pool. Offloads all blocking UDS connect/send/recv
* from the epoll reactor thread, keeping the event loop non-blocking.
*
* CSCI 599: Network Systems for Cloud Computing
* University of Southern California
*/
#ifndef __DISPATCH_POOL_HPP__
#define __DISPATCH_POOL_HPP__
#include <functional>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <vector>
#include <atomic>
#include "log.hpp"
// DispatchPool: Fixed-size thread pool for handling blocking UDS I/O.
// The Reactor thread pushes tasks here and returns immediately.
// Pool threads do all the blocking connect/send/recv work.
class DispatchPool {
public:
static const int DEFAULT_THREADS = 64;
private:
std::vector<std::thread> _threads;
std::queue<std::function<void()>> _tasks;
std::mutex _mtx;
std::condition_variable _cv;
std::atomic<bool> _stop;
public:
explicit DispatchPool(int nthreads = DEFAULT_THREADS) : _stop(false) {
for (int i = 0; i < nthreads; ++i) {
_threads.emplace_back([this]() {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(_mtx);
_cv.wait(lock, [this]() {
return _stop.load() || !_tasks.empty();
});
if (_stop.load() && _tasks.empty()) return;
task = std::move(_tasks.front());
_tasks.pop();
}
task();
}
});
}
logMessage(NORMAL, "[DispatchPool] Started with %d threads.", nthreads);
}
~DispatchPool() {
_stop.store(true);
_cv.notify_all();
for (auto& t : _threads) {
if (t.joinable()) t.join();
}
}
void push(std::function<void()> task) {
{
std::lock_guard<std::mutex> lock(_mtx);
_tasks.push(std::move(task));
}
_cv.notify_one();
}
size_t pending_count() {
std::lock_guard<std::mutex> lock(_mtx);
return _tasks.size();
}
};
#endif // __DISPATCH_POOL_HPP__