Why is std::async slow compared to simple detached threads? Why is std::async slow compared to simple detached threads? multithreading multithreading

Why is std::async slow compared to simple detached threads?


One key difference is that the future returned by async joins the thread when the future is destroyed, or in your case, replaced with a new value.

This means it has to execute someTask() and join the thread, both of which take time. None of your other tests are doing that, where they simply spawn them independently.


sts::async returns a special std::future. This future has a ~future that does a .wait().

So your examples are fundamentally different. The slow ones actually do the tasks during your timing. The fast ones just queue up the tasks, and forget how to ever know the task is done. As the behaviour of programs that let threads last past the end of main is unpredictable, one should avoid it.

The right way to compare the tasks is to store the resulting future when genersting, and before the timer ends either .wait()/.join() them all, or avoid destroying the objects until after the timer expires. This last case, however, makes the sewuential version look worse than it is.

You do need to join/wait before starting the next test, as otherwise you are stealing resources from their timing.

Note that moved futures remove the wait from the source.