-
Notifications
You must be signed in to change notification settings - Fork 2
/
threadpool.hpp
41 lines (33 loc) · 970 Bytes
/
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
/*! \file
\brief A minimalistic thread pool implementation.
Code based on:
https://codereview.stackexchange.com/questions/79323/simple-c-thread-pool
https://github.com/vit-vit/CTPL/blob/master/ctpl_stl.h
*/
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <atomic>
#include <condition_variable>
#include <functional>
class ThreadPool
{
public:
explicit ThreadPool(size_t thread_count);
~ThreadPool();
void schedule( const std::function<void()>&);
void waitAll() const;
private:
// Make the thread pool noncopyable
ThreadPool(const ThreadPool&) = delete;
ThreadPool(ThreadPool &&) = delete;
ThreadPool & operator=(const ThreadPool&) = delete;
ThreadPool & operator=(const ThreadPool&&) = delete;
std::vector<std::thread> workers_;
std::queue<std::function<void()>> tasks_;
std::atomic_uint task_count_;
std::atomic_bool stop_;
std::mutex mutex_;
std::condition_variable condition_;
};