A pool of persistent worker threads for concurrent task execution.
More...
|
| | ThreadPool_Advanced (size_t num_threads) |
| | Initializes the thread pool with a specified number of threads.
|
| |
| template<class F > |
| auto | enqueue (F f) -> std::future< decltype(f())> |
| | Adds a task to the pool and returns a future for the result.
|
| |
| | ~ThreadPool_Advanced () |
| | Gracefully shuts down the thread pool.
|
| |
A pool of persistent worker threads for concurrent task execution.
- The ThreadPool manages a fixed set of threads that pull tasks from a thread-safe queue. It supports tasks with arbitrary return values via the enqueue method.
Definition at line 59 of file ThreadPool_Advanced.cpp.
◆ ThreadPool_Advanced()
| ThreadPool_Advanced::ThreadPool_Advanced |
( |
size_t |
num_threads | ) |
|
|
inline |
Initializes the thread pool with a specified number of threads.
- Parameters
-
| num_threads | Number of worker threads to create. |
Definition at line 96 of file ThreadPool_Advanced.cpp.
96 : stop(false) {
97 for (size_t i = 0; i < num_threads; ++i) {
98 workers.emplace_back(&ThreadPool_Advanced::workerLoop, this);
99 }
100 }
◆ ~ThreadPool_Advanced()
| ThreadPool_Advanced::~ThreadPool_Advanced |
( |
| ) |
|
|
inline |
Gracefully shuts down the thread pool.
- Sets the stop flag, notifies all workers, and joins them to ensure all threads finish execution.
Definition at line 133 of file ThreadPool_Advanced.cpp.
133 {
134 stop = true;
135 cv.notify_all();
136 for (std::thread &worker : workers) {
137 if (worker.joinable()) worker.join();
138 }
139 }
◆ enqueue()
template<class F >
| auto ThreadPool_Advanced::enqueue |
( |
F |
f | ) |
-> std::future<decltype(f())> |
|
inline |
Adds a task to the pool and returns a future for the result.
- Uses template meta-programming to deduce the return type of the provided function.
- Template Parameters
-
| F | Type of the function or functor. |
- Parameters
-
- Returns
- std::future<decltype(f())> A future object to access the task's return value.
Definition at line 110 of file ThreadPool_Advanced.cpp.
110 {
111 using ReturnType = decltype(f());
112
113
114 auto task = std::make_shared<std::packaged_task<ReturnType()>>(f);
115
116 std::future<ReturnType> res = task->get_future();
117
118 {
119 std::unique_lock<std::mutex> lock(queue_mtx);
120
121 tasks.emplace([task]() { (*task)(); });
122 }
123
124 cv.notify_one();
125 return res;
126 }
Referenced by main().
The documentation for this class was generated from the following file: