1#ifndef SRC_SCANNER_LIB_THREAD_POOL_H_
2#define SRC_SCANNER_LIB_THREAD_POOL_H_
4#include <condition_variable>
33 explicit ThreadPool(std::size_t num_threads = 0);
69 template <
class F,
class... Args>
70 auto Enqueue(F&& f, Args&&... args)
71 -> std::future<std::invoke_result_t<F, Args...>>;
77 std::queue<std::function<void()>>
tasks_;
84template <
class F,
class... Args>
86 -> std::future<std::invoke_result_t<F, Args...>> {
87 using return_type = std::invoke_result_t<F, Args...>;
89 auto task = std::make_shared<std::packaged_task<return_type()>>(
90 std::bind(std::forward<F>(f), std::forward<Args>(args)...));
92 std::future<return_type> res = task->get_future();
94 std::unique_lock<std::mutex> lock(queue_mutex_);
98 throw std::runtime_error(
"Enqueue on stopped ThreadPool");
101 tasks_.emplace([task]() { (*task)(); });
103 condition_.notify_one();
Manages a pool of worker threads to execute tasks concurrently.
Definition thread_pool.h:26
std::queue< std::function< void()> > tasks_
Definition thread_pool.h:77
std::condition_variable condition_
Definition thread_pool.h:80
void Worker()
Definition thread_pool.cpp:42
auto Enqueue(F &&f, Args &&... args) -> std::future< std::invoke_result_t< F, Args... > >
Enqueues a task for execution by a worker thread.
Definition thread_pool.h:85
std::vector< std::thread > workers_
Definition thread_pool.h:76
ThreadPool(ThreadPool &&)=delete
ThreadPool & operator=(const ThreadPool &)=delete
ThreadPool(const ThreadPool &)=delete
~ThreadPool()
Destructor. Initiates a graceful shutdown and joins all threads.
Definition thread_pool.cpp:22
ThreadPool & operator=(ThreadPool &&)=delete
void Stop()
Initiates the shutdown of the thread pool.
Definition thread_pool.cpp:31
std::atomic< bool > stop_
Definition thread_pool.h:81
std::mutex queue_mutex_
Definition thread_pool.h:79