C++ Concurrency Sandbox
Loading...
Searching...
No Matches
ThreadPool_Advanced Class Reference

A pool of persistent worker threads for concurrent task execution. More...

Collaboration diagram for ThreadPool_Advanced:

Public Member Functions

 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.
 

Detailed Description

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.

Constructor & Destructor Documentation

◆ ThreadPool_Advanced()

ThreadPool_Advanced::ThreadPool_Advanced ( size_t  num_threads)
inline

Initializes the thread pool with a specified number of threads.

Parameters
num_threadsNumber 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 }

Member Function Documentation

◆ enqueue()

template<class F >
auto ThreadPool_Advanced::enqueue ( 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
    FType of the function or functor.
    Parameters
    fThe task to execute.
    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 // Packaged tasks handle the storage of the return value or exceptions.
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 // Lambda captures the shared_ptr by value to extend its lifetime.
121 tasks.emplace([task]() { (*task)(); });
122 }
123
124 cv.notify_one();
125 return res;
126 }

Referenced by main().

Here is the caller graph for this function:

The documentation for this class was generated from the following file: