In this example, we’ll look at how to implement a worker pool using threads and a thread-safe queue.
Here’s the worker function, of which we’ll run several concurrent instances. These workers will receive work on the jobs queue and send the corresponding results on the results queue. We’ll sleep a second per job to simulate an expensive task.
In order to use our pool of workers, we need to send them work and collect their results. We make 2 thread-safe queues for this.
This starts up 3 worker threads, initially waiting because there are no jobs yet.
Here we send 5 jobs to the jobs queue.
Finally, we wait for all the jobs to be processed and results to be collected. This also ensures that the worker threads have finished. An alternative way to wait for multiple threads is to use std::future.
Our running program shows the 5 jobs being executed by various workers. The program only takes about 2 seconds despite doing about 5 seconds of total work because there are 3 workers operating concurrently.
To compile and run the program:
This C++ implementation uses std::thread for concurrency and custom thread-safe queues for job distribution and result collection. The overall structure and behavior are similar to the original example, demonstrating the concept of worker pools in C++.