LIPH's C++ Codes
threadpool.h
Go to the documentation of this file.
1#ifndef LIPH_CONCURRENCY_THREADPOOL_H_
2#define LIPH_CONCURRENCY_THREADPOOL_H_
3
4#include <atomic>
5#include <condition_variable>
6#include <functional>
7#include <mutex>
8#include <stdexcept>
9#include <thread>
10#include <vector>
11
13
14namespace liph {
15
17public:
18 threadpool(size_t size = 0);
20
21 threadpool(const threadpool&) = delete;
23 threadpool& operator=(const threadpool&) = delete;
25
26 void start();
27 void stop();
28
29 template <class Function, class... Args>
30 void add(Function&& func, Args&&...args) {
31 if (stopped_) throw std::runtime_error("Thread pool already stopped or not started");
32 std::unique_lock<std::mutex> lock(lock_); // need lock here
33 tasks_.push(std::bind(func, std::forward<Args>(args)...));
34 cv_.notify_one();
35 }
36
37 unsigned int size() const { return size_; }
38
39private:
40 using task = std::function<void()>;
41 void run();
42 task take();
43
44private:
45 unsigned int size_;
46 std::atomic<bool> stopped_;
47 std::atomic<bool> shutdown_;
48 std::vector<std::thread> threads_;
49 std::mutex lock_;
50 std::condition_variable cv_;
52};
53
54} // namespace liph
55
56#endif // LIPH_CONCURRENCY_THREADPOOL_H_
#define func(V)
void push(const T &v)
Definition: blocking_queue.h:25
Definition: threadpool.h:16
threadpool & operator=(const threadpool &)=delete
threadpool(threadpool &&)=delete
void add(Function &&func, Args &&...args)
Definition: threadpool.h:30
threadpool & operator=(threadpool &&)=delete
threadpool(size_t size=0)
Definition: threadpool.cpp:5
unsigned int size() const
Definition: threadpool.h:37
~threadpool()
Definition: threadpool.cpp:12
threadpool(const threadpool &)=delete
void start()
Definition: threadpool.cpp:14
void stop()
Definition: threadpool.cpp:20
Definition: algorithm.h:10