14 #ifndef BOUNDED_THREAD_POOL_H
15 #define BOUNDED_THREAD_POOL_H
21 #include <condition_variable>
28 std::vector<std::thread> threads;
29 std::queue<std::function<void()>> tasks;
30 std::atomic<bool> b_running;
32 std::condition_variable cnd_buffer_full;
33 std::condition_variable cnd_buffer_empty;
39 threads.push_back(std::thread(&BoundedThreadPool::worker,
this));
45 std::unique_lock<std::mutex> lock(mtx_queue);
46 cnd_buffer_empty.wait(lock, [
this]
47 {
return !tasks.empty() || !b_running; });
50 std::function<void()> task = std::move(tasks.front());
52 cnd_buffer_full.notify_one();
65 catch (
const std::exception &e)
67 std::cerr << e.what() << std::endl;
79 std::unique_lock<std::mutex> lock(mtx_queue);
80 cnd_buffer_full.wait(lock, [
this]
81 {
return ((
int)tasks.size() <
limit); });
82 tasks.push(std::function<
void()>(task));
83 cnd_buffer_empty.notify_one();
86 template <
typename T,
typename... A>
95 std::unique_lock<std::mutex> lock(mtx_queue);
96 cnd_buffer_full.wait(lock, [
this]
97 {
return tasks.empty(); });
110 int n_threads_max = std::thread::hardware_concurrency();
113 this->n_threads = n_threads_max;
140 cnd_buffer_empty.notify_all();
BoundedThreadPool(int n_threads, int limit)
void init(int n_threads, int limit)
void push_task(const T &task)
void push_task(const T &task, const A &...args)
BoundedThreadPool(int n_threads)
void wait_for_completion()