forked from s4mu313/webcam-http-streamer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththread_pool.h
66 lines (53 loc) · 1.73 KB
/
thread_pool.h
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
#ifndef THREAD_POOL_H
#define THREAD_POOL_H
#include <mutex>
#include <thread>
#include <vector>
#include <atomic>
class Thread_pool {
private:
class guarded_thread : std::thread {
public:
using std::thread::thread;
~guarded_thread()
{ if (joinable()) join(); }
};
public:
Thread_pool() = default;
~Thread_pool() = default;
Thread_pool(Thread_pool&&) = delete;
Thread_pool(const Thread_pool&) = delete;
Thread_pool& operator=(Thread_pool&&) = delete;
Thread_pool& operator=(const Thread_pool&) = delete;
template<typename F, typename... Args>
void
exec(F&& f, Args&&... args)
{
std::unique_lock<std::mutex> lck(mtx);
if (_pos.size() == 0) {
_thread_list.push_back(std::make_unique<guarded_thread>([&](std::size_t id, F& f, Args&... args) {
f(args...);
std::unique_lock<std::mutex> lck(mtx);
_pos.push_back(id);
}, _thread_list.size(), std::ref(f), std::ref(args)...));
return;
}
_thread_list[_pos[0]] = std::make_unique<guarded_thread>([&](std::size_t id, F& f, Args&... args) {
f(args...);
std::unique_lock<std::mutex> lck(mtx);
_pos.push_back(id);
}, _pos[0], std::ref(f), std::ref(args)...);
_pos.erase(_pos.begin());
}
std::size_t
active()
{
std::unique_lock<std::mutex> lck(mtx);
return _thread_list.size() - _pos.size();
}
private:
std::mutex mtx;
std::vector<std::unique_ptr<guarded_thread>> _thread_list;
std::vector<std::size_t> _pos;
};
#endif // THREAD_POOL_H