Search code examples
c++multithreadingc++11stdasync

How can a function run "as if" on a new thread without doing so?


Per [futures.async]/3 bullet 1 of the C++ Standard, when a function f is passed to std::async with the std::launch::async launch policy, f will run "as if in a new thread of execution".

Given that f can do anything, including loop infinitely and block forever, how can an implementation offer the behavior of f running on its own thread without actually running it on its own thread? That is, how can an implementation take advantage of the "as if" wiggle room the Standard provides?


Solution

  • Looking in the C++ refs as appear here and here, it seems that the "as if" goal is to let the library implementer some degree of freedom. For example, it says

    as if spawned by std::thread(std::forward(f), std::forward(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.

    in the first source, and

    as if a thread object is constructed with fn and args as arguments, and accessing the shared state of the returned future joins it

    in the second. So it looks like the behavior is similar to that of std::thread but might be implemented in a different way. This is interesting, since the phrase thread of execution you quote here is distinguishable from std::thread. Still, it seems that both sources understand the as-if that way.

    Another option might be, as suggested by François Andrieux to allow usage of threadpool, as expressed in the first source:

    The template function async runs the function f asynchronously (potentially in a separate thread which may be part of a thread pool)