C++11 Concurrency Tutorial: Part 4

After a two-week break, attending the Intel Developers Forum and StrangeLoop, I finally had the time to record the fourth tutorial in the series. This time I’m showing how futures and promises work together to enable the passing of results back from threads. I also show how this process of calling a function asynchronously can be simplified using async. Next time I’ll talk more about async tasks and parallelism.Follow @BartoszMilewski
(You can also follow me on Google+, if you search for Bartosz Milewski.)

I would much appreciate if you said something about how to do this in a compiler that is not from the future though. Boost has promise and future but no async? Also using std::current_exception was very interesting, but its seems like magic. I’m curious how it is implemented. How can future::get translate std::current_exception into the actual exception type and re-throw that?

I’m using VS 2010 with Just::Thread library — these are available now, although the library is not free (well, neither is Visual Studio).

Using boost you’d have to create a thread, pass it a promise, and block on a future. I described how it’s done using std::thread in C++11 in one of the previous tutorials. It’s easy to translate it into boost.

The C++ runtime has access to the caught exception inside the catch block, so it can’t be too hard for it to implement current_exception. I don’t know the details though.

Hello. I found that with gcc 4.7 i can call future::get with function of return type void. And without get() being called, future object gets destroyed right after it was created, even without executing function i passed to async. So which implementation is closer to standard?

@Anatoly: Did you mean “can” or “cannot”? For void futures you can always call wait() instead of get(). However, the Standard says that it’s okay to call get() for a void future:

void future<void>::get();

Whether an async function is executed even if get/wait is not called depends on launch policy: async or deferred. For async it will be executed. but for defferred it won’t. The default is async|deferred, which leaves the decision to the runtime. If the runtime choses the deferred policy, it won’t execute the function unless you call get or wait.