File Scanner 1.0.0
A high-performance C++ malicious file scanner.
Loading...
Searching...
No Matches
thread_pool.h
Go to the documentation of this file.
1#ifndef SRC_SCANNER_LIB_THREAD_POOL_H_
2#define SRC_SCANNER_LIB_THREAD_POOL_H_
3
4#include <condition_variable>
5
6#include <atomic>
7#include <functional>
8#include <future>
9#include <mutex>
10#include <queue>
11#include <thread>
12#include <type_traits>
13#include <vector>
14
15namespace scanner {
16
27public:
33 explicit ThreadPool(std::size_t num_threads = 0);
34
42
43 ThreadPool(const ThreadPool&) = delete;
44 ThreadPool& operator=(const ThreadPool&) = delete;
47
55 void Stop();
56
69 template <class F, class... Args>
70 auto Enqueue(F&& f, Args&&... args)
71 -> std::future<std::invoke_result_t<F, Args...>>;
72
73private:
74 void Worker();
75
76 std::vector<std::thread> workers_;
77 std::queue<std::function<void()>> tasks_;
78
79 std::mutex queue_mutex_;
80 std::condition_variable condition_;
81 std::atomic<bool> stop_{false};
82};
83
84template <class F, class... Args>
85auto ThreadPool::Enqueue(F&& f, Args&&... args)
86 -> std::future<std::invoke_result_t<F, Args...>> {
87 using return_type = std::invoke_result_t<F, Args...>;
88
89 auto task = std::make_shared<std::packaged_task<return_type()>>(
90 std::bind(std::forward<F>(f), std::forward<Args>(args)...));
91
92 std::future<return_type> res = task->get_future();
93 {
94 std::unique_lock<std::mutex> lock(queue_mutex_);
95
96 // Don't allow enqueueing after stopping.
97 if (stop_.load()) {
98 throw std::runtime_error("Enqueue on stopped ThreadPool");
99 }
100
101 tasks_.emplace([task]() { (*task)(); });
102 }
103 condition_.notify_one();
104 return res;
105}
106
107} // namespace scanner
108
109#endif // SRC_SCANNER_LIB_THREAD_POOL_H_
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
Definition domain.h:12