C++ Concurrency Sandbox
Loading...
Searching...
No Matches
ThreadPool_Lambda Class Reference
Collaboration diagram for ThreadPool_Lambda:

Public Member Functions

 ThreadPool_Lambda (size_t num_threads)
 Construct a new Thread Pool object.
 
template<class F >
auto enqueue (F f) -> std::future< decltype(f())>
 Enqueues a function for asynchronous execution.
 
 ~ThreadPool_Lambda ()
 Destroy the Thread Pool object.
 

Detailed Description

Definition at line 30 of file ThreadPool_Lambda.cpp.

Constructor & Destructor Documentation

◆ ThreadPool_Lambda()

ThreadPool_Lambda::ThreadPool_Lambda ( size_t  num_threads)
inline

Construct a new Thread Pool object.

Parameters
num_threadsThe number of worker threads to spawn.

Definition at line 68 of file ThreadPool_Lambda.cpp.

68 : stop(false) {
69 for (size_t i = 0; i < num_threads; ++i) {
70 workers.emplace_back(&ThreadPool_Lambda::workerLoop, this);
71 }
72 }

◆ ~ThreadPool_Lambda()

ThreadPool_Lambda::~ThreadPool_Lambda ( )
inline

Destroy the Thread Pool object.

  • Signals all workers to stop and joins them. Tasks already in the queue will be completed before destruction finishes.

Definition at line 110 of file ThreadPool_Lambda.cpp.

110 {
111 stop = true;
112 cv.notify_all(); // Wake up all threads to see the stop flag
113 for (std::thread &worker : workers) {
114 if (worker.joinable()) worker.join();
115 }
116 }

Member Function Documentation

◆ enqueue()

template<class F >
auto ThreadPool_Lambda::enqueue ( f) -> std::future<decltype(f())>
inline

Enqueues a function for asynchronous execution.

  • This template method wraps a function into a packaged_task, pushes it to the queue, and returns a future to track the result.
  • Template Parameters
    FThe type of the function to be executed.
    Parameters
    fThe function (or lambda/bind) to execute.
    Returns
    std::future<decltype(f())> A future object to retrieve the function's result.

Definition at line 83 of file ThreadPool_Lambda.cpp.

83 {
84 // 1. Determine the return type of the function dynamically
85 using ReturnType = decltype(f());
86
87 // 2. Wrap the function in a packaged_task shared pointer
88 // Packaged tasks can only be moved, so we use shared_ptr to allow copying into the wrapper lambda.
89 auto task = std::make_shared<std::packaged_task<ReturnType()>>(f);
90
91 // 3. Extract the future "ticket" before sending the task to the queue
92 std::future<ReturnType> res = task->get_future();
93
94 {
95 std::unique_lock<std::mutex> lock(queue_mtx);
96
97 // 4. Wrap the task in a void() lambda so it fits our Task queue
98 tasks.emplace([task]() { (*task)(); });
99 }
100
101 cv.notify_one(); // Wake up one idle worker
102 return res; // Return the future to the caller
103 }

Referenced by main().

Here is the caller graph for this function:

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