93

I'm trying to explore all the options of the new C++11 standard in depth, while using std::async and reading its definition, I noticed 2 things, at least under linux with gcc 4.8.1 :

  • it's called async, but it got a really "sequential behaviour", basically in the row where you call the future associated with your async function foo, the program blocks until the execution of foo it's completed.
  • it depends on the exact same external library as others, and better, non-blocking solutions, which means pthread, if you want to use std::async you need pthread.

at this point it's natural for me asking why choosing std::async over even a simple set of functors ? It's a solution that doesn't even scale at all, the more future you call, the less responsive your program will be.

Am I missing something ? Can you show an example that is granted to be executed in an async, non blocking, way ?

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
user2485710
  • 9,451
  • 13
  • 58
  • 102
  • @rsaxvc where you call the async function, for example `future.get()` – user2485710 Jul 31 '13 at 06:44
  • 4
    Your assumptions are wrong. async() is designed to provide a synchronization point so you can get the result of the function being evaluated asynchronously. – DanielKO Jul 31 '13 at 07:04
  • C++'s current idea of "async" doesn't really bring anything significant (other than portability) to the table in comparison to other options. Once it gets continuation-on-completion support (which is a vital part of what virtually every other platform calls "async"), I suspect you'll find many more uses for it. – Cory Nelson Feb 17 '14 at 04:52
  • This shows how async makes getting return values super simple: https://stackoverflow.com/questions/7686939/c-simple-return-value-from-stdthread – Ciro Santilli OurBigBook.com May 05 '19 at 09:47

5 Answers5

100
  • it's called async, but it got a really "sequential behaviour",

No, if you use the std::launch::async policy then it runs asynchronously in a new thread. If you don't specify a policy it might run in a new thread.

basically in the row where you call the future associated with your async function foo, the program blocks until the execution of foo it's completed.

It only blocks if foo hasn't completed, but if it was run asynchronously (e.g. because you use the std::launch::async policy) it might have completed before you need it.

  • it depends on the exact same external library as others, and better, non-blocking solutions, which means pthread, if you want to use std::async you need pthread.

Wrong, it doesn't have to be implemented using Pthreads (and on Windows it isn't, it uses the ConcRT features.)

at this point it's natural for me asking why choosing std::async over even a simple set of functors ?

Because it guarantees thread-safety and propagates exceptions across threads. Can you do that with a simple set of functors?

It's a solution that doesn't even scale at all, the more future you call, the less responsive your program will be.

Not necessarily. If you don't specify the launch policy then a smart implementation can decide whether to start a new thread, or return a deferred function, or return something that decides later, when more resources may be available.

Now, it's true that with GCC's implementation, if you don't provide a launch policy then with current releases it will never run in a new thread (there's a bugzilla report for that) but that's a property of that implementation, not of std::async in general. You should not confuse the specification in the standard with a particular implementation. Reading the implementation of one standard library is a poor way to learn about C++11.

Can you show an example that is granted to be executed in an async, non blocking, way ?

This shouldn't block:

auto fut = std::async(std::launch::async, doSomethingThatTakesTenSeconds);
auto result1 = doSomethingThatTakesTwentySeconds();
auto result2 = fut.get();

By specifying the launch policy you force asynchronous execution, and if you do other work while it's executing then the result will be ready when you need it.

WiSaGaN
  • 46,887
  • 10
  • 54
  • 88
Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521
  • 3
    Very nice answer! I have a question about the last example: although you can force the `doSomethingThatTakesTenSeconds` to be launched in a separate thread, but you cannot force it to run "immediately", right? If that's the case, then the 'fut.get()' could still block. – GuLearn Dec 24 '13 at 16:00
  • 23
    Yes, but if it takes that long for a new thread to start then your system is horribly overloaded or its scheduler is rubbish. – Jonathan Wakely Dec 29 '13 at 10:38
  • 1
    [I measured on coliru](http://coliru.stacked-crooked.com/a/014dac336cc8374c) that there is around 100µs to 300µs of latency. Around 33% of a millisecond max is good. I would be curious to know what that code does on windows VS vs linux g++ on the same box. – doug65536 May 19 '16 at 05:36
  • 1
    How does implementation decide the policy? For example, I would like `std::launch::deferred` when the computation is cheaper than thread scheduling (which may go to kernel)? (Sorry I'm not familiar with `std::thread` and assume that it's scheduled by OS.) – Franklin Yu Jul 09 '17 at 15:08
  • 1
    Ask your own question, don't hijack the comments in other questions. – Jonathan Wakely Feb 01 '18 at 08:48
  • 2
    "and on Windows it isn't, it uses the ConcRT features" unless one uses GCC on Windows, in which case it may use WinPthreads or similar – uLoop Mar 24 '18 at 18:44
77

If you need the result of an asynchronous operation, then you have to block, no matter what library you use. The idea is that you get to choose when to block, and, hopefully when you do that, you block for a negligible time because all the work has already been done.

Note also that std::async can be launched with policies std::launch::async or std::launch::deferred. If you don't specify it, the implementation is allowed to choose, and it could well choose to use deferred evaluation, which would result in all the work being done when you attempt to get the result from the future, resulting in a longer block. So if you want to make sure that the work is done asynchronously, use std::launch::async.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Why it "needs" to block ? why not assuming that an async function needs to be executed as soon as possible and give the ability to retrieve just the result, and most importantly, if the C++11 is proposing a new threading model why not using it in the definition of std::async ? std::async doesn't even grant that more than 1 thread will be used. Also AFAIK methods under std::launch:: are just wrappers to future , it's the same blocking concept of execution. – user2485710 Jul 31 '13 at 06:41
  • 2
    @user2485710 it needs to block when you retrieve the result, *if* you need the result in the launching thread. It cannot use the result if the result is not ready. So if you go to get the result, you have to wait until it is ready. If it is already ready, then the blocking time will be negligible. – juanchopanza Jul 31 '13 at 06:45
  • 2
    @user2485710 also note, in my experience, `std::async` has asynchronous behaviour, as expected. – juanchopanza Jul 31 '13 at 06:48
  • can you provide an example where the async behaviour of this is observable ? – user2485710 Jul 31 '13 at 06:49
  • 6
    @user2485710 http://coliru.stacked-crooked.com/view?id=506ad2d5bdda4d6181aeaa8926c7dd89-80162bcd59d15b475a9bf39ab35abb94 – R. Martinho Fernandes Jul 31 '13 at 06:57
  • @juanchopanza, there's a difference between "need to block" and "may block" :) – chill Jul 31 '13 at 12:55
  • @chill It *needs* to block if you *need* the result of the future. There is no getting around that. – juanchopanza Jul 31 '13 at 12:57
  • @juanchopanza, and if the result is already ready, it "needs" to block waiting for what? – chill Jul 31 '13 at 12:59
  • 1
    @chill it blocks to return the result. Just like any synchronous function would. Getting from the future constitutes a synchronization point. – juanchopanza Jul 31 '13 at 13:00
  • 2
    @juanchopanza, ok, not going to turn this into a chat, what you say makes absolutely no sense, "blocking" in the context of process/thread execution has the well accepted semantics of putting the execution out of "running" into some kind of a "waiting" state, neither of which *necessarily* happens here. Over. – chill Jul 31 '13 at 13:05
  • 1
    You _have_ to wait for sure, but it doesn't mean you _have_ to block. In particular, continuations and co_await are two ways to handle waiting without blocking (and more importantly - without thread context switching which is inevitably caused by blocking). – No-Bugs Hare Mar 24 '18 at 07:50
19

I think your problem is with std::future saying that it blocks on get. It only blocks if the result isn't already ready.

If you can arrange for the result to be already ready, this isn't a problem.

There are many ways to know that the result is already ready. You can poll the future and ask it (relatively simple), you could use locks or atomic data to relay the fact that it is ready, you could build up a framework to deliver "finished" future items into a queue that consumers can interact with, you could use signals of some kind (which is just blocking on multiple things at once, or polling).

Or, you could finish all the work you can do locally, and then block on the remote work.

As an example, imagine a parallel recursive merge sort. It splits the array into two chunks, then does an async sort on one chunk while sorting the other chunk. Once it is done sorting its half, the originating thread cannot progress until the second task is finished. So it does a .get() and blocks. Once both halves have been sorted, it can then do a merge (in theory, the merge can be done at least partially in parallel as well).

This task behaves like a linear task to those interacting with it on the outside -- when it is done, the array is sorted.

We can then wrap this in a std::async task, and have a future sorted array. If we want, we could add in a signally procedure to let us know that the future is finished, but that only makes sense if we have a thread waiting on the signals.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
3

In the reference: http://en.cppreference.com/w/cpp/thread/async

If the async flag is set (i.e. policy & std::launch::async != 0), then async executes the function f on a separate thread of execution as if spawned by std::thread(f, args...), except that if the function f returns a value or throws an exception, it is stored in the shared state accessible through the std::future that async returns to the caller.

It is a nice property to keep a record of exceptions thrown.

Community
  • 1
  • 1
fatihk
  • 7,789
  • 1
  • 26
  • 48
  • that's not a guarantee, according to the standard I can't see why a given C++11 implementation is forced to use something something different than an "usual" single threaded execution. – user2485710 Jul 31 '13 at 06:43
  • 2
    @user2485710 it is forced because the standard says so: "as if in a new thread of execution" (§30.6.8/3). – R. Martinho Fernandes Jul 31 '13 at 06:54
  • 1
    @user2485710: and "as if in a new thread of execution" has observable effects, for instance thread locals. Of course, if the compiler can prove that it's not observable, it's free to execute it synchronously under the as-if rule, but this is a quality-of-implementation issue. – JohannesD Jul 31 '13 at 07:35
0

http://www.cplusplus.com/reference/future/async/

there are three type of policy,

  1. launch::async
  2. launch::deferred
  3. launch::async|launch::deferred

by default launch::async|launch::deferred is passed to std::async.

roschach
  • 8,390
  • 14
  • 74
  • 124
msoodb
  • 23
  • 1
  • 7