Sunday, 3 July 2016

Completion thread pool for C++

This is an implementation of a thread pool for c++ I wrote a month ago. It has two classes, the general ThreadPool that accepts new tasks and returns std::future to receive the result from them and the CompletionThreadPool that works more along the lines of ExecutionCompletionService from java. The CompletionThreadPool Based on regular thread pool allowa to retrieve tasks results in order of the completion. It can be used as follows. Create a task to be submitted to the pool:
int f(int sleep_time) {
    return sleep_time;
Create CompletionThreadPool instance with designated task result type:
CompletionThreadPool completionThreadPool;
Submit any number of tasks for execution (they will be enqueued for execution immediately):
completionThreadPool.Submit(f, 5);
completionThreadPool.Submit(f, 1);
Block waiting for the results in order of their completion:
std::future firstCompleted = completionThreadPool.Take();
std::future secondCompleted = completionThreadPool.Take();
The source is located at github. There is also a qt sample application that uses CompletionThreadPool to download images in separate threads and show them in a window in order of readiness.