Posted Joe Chu cpp3 minutes read (About 492 words)0 visits
Theading Pool
Basic threading pool
Advanced threading pool
1. Basic Threading Pool
In a simple threading pool setup, there’s a set number of threads and a queue for tasks. Tasks are processed in a first-in, first-out (FIFO) manner. Any idle threads will promptly handle the task at the front of the queue.
A few things to note.
Line 22 added predicate to prevent spurious wakeup.
Once the thread is blocked by the wait(), will automatically call lock.unlock()
intmain(){ ThreadPool pool(3); std::cout << "adding tasks\n"; for (int i = 0; i < 15; i++) { pool.enqueue([i](){ std::cout << "Task " << i << " executed by thread " << std::this_thread::get_id() << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); }); } std::cout << "finish adding tasks\n";
std::cout << "This is main thread running\n";
return0; }
Advanced Threading Pool
A sophisticated threading pool implementation employs a design where each individual thread is assigned its own distinct task queue. Tasks are added to these queues, and each thread processes the tasks present in its corresponding queue in sequential order.