Thread Pool

class Pool

Utility for parallel computing.

This class allow the user to enqueue a list of jobs to process and then to process them using as many subthreads as wanted.

//Increase the value of an int
void sumInt(int &val, std::mutex &mtx)
{
     std::unique_lock<std::mutex> lock(mtx);
     std::this_thread::sleep_for(std::chrono::milliseconds(100));
     ++val;
}

 //Create a pool, with 4 workers
 thread::Pool pool(4);
 int val(0);
 int target(20);
 std::mutex mtx;
 //Enqueu 20 calls to sumInt
 for(int i(0); i<target; ++i)
 {
     pool.enqueue(std::bind(sumInt, std::ref(val), std::ref(mtx)));
 }
 //Launch the execution and wait for termination
 pool.joinAll();

Public Functions

inline void enqueue(job_t job)

Add a job in the queue.

Parameters:

job – the job

inline std::optional<job_t> dequeue()

Thread safe accessor to the next job.

Returns:

the next job if any, {} otherwise

inline void joinAll()

Launch all the threads and wait for termination.

inline explicit Pool(size_t nworkers = 0)

Constructor.

Parameters:

nworkers – the number of threads