Using a Single Threaded Functor in Multiple Threads with Futures in C++

Author:Emre Şahin
Date:<>

Multithreaded programming requires a shift of paradigm when it comes to return values of functions. C++11 provides `std::async <http://en.cppreference.com/w/cpp/thread/async>`__ to run functions asynchronously but this is not available in older versions.

My current project on word spotting on historical documents is fairly complete in functionality but I decided that searching word images on page images concurrently is necessary for speed up. I’m already using Boost for many of the functionality and instead of creating a dependency on not yet mature C++11 support in various compilers, I decided to use =boost::thread=s.

Suppose we have a functor like

and we want to use this functor in multiple threads. We can’t simply do

because task does not return a SearchResult.

Instead we need to store results within the object and retrieve them after they are generated.

I didn’t want to change the interface of Search_t, because multithreading should be optional and other parts of the program may depend on this interface. Instead a wrapper class that runs these threads with a similar interface looked a better solution.

This way, it becomes much more straightforward to use multithreading in a loop:

This way, we kept the Search_t class intact and used a much simpler approach in the loop.