2012-05-09 CPlusPlus11

The future of threading

A major concern these days is how to handle all these cores we have available everywhere. How to program them? C++11 tries to address this problem by including support for threads in the standard library.

The basic stuff for starting and joining threads and synchronization with the help of different types of mutexes is there. Support for low level atomic operations is there to. We might come back to those issues later. Now we will look at the high level support provided by futures and async.

The basic functionality is this. The function async takes nearly anything executable and returns a future object. When you want to have the result from the async call you call the get method on the future object.

   auto f = async(doIt);
   auto resultFromDoIt = f.get();

Very simple in its basic form. But there is more...

The async execution can be controlled in more detail by specifying a launch policy. It can be launched either async or deferred. If it is called with async policy it will be started asynchronously if it can. You'll get an exception otherwise.

   auto f = async(launch::async, doIt);

When launch::deferred is used it is guaranteed that the function wont run until get is called. What good this is for is another question. Debugging could be one use of it.

Besides the get method there are also methods to poll for a result.

I also said async could be called with almost anything that could be executed. It can take functions, member functions and lambdas. You can pass arguments to the functions.

Be careful though when passing arguments so that they don't go out of scope before the asynchronous computation is finished. All these types of problems are of course still relevant for asynch. Passing arguments by value is one solution to that problem.