我什么时候需要使用std :: async(std :: launch :: async,func())而不是func()?(When should I need to use std::async(std::launch::async, func()) instead of func()?)

我没有得到使用std::async和std::lauch::async标志的原因,而不是简单地调用传递给std::async的函数。 有特价保证吗?

I don't get the reason behind using std::async with std::lauch::async flag, instead of simply calling the function passed to std::async. Are there any specials guarantees?

最满意答案

根据文档 ,有一个重载只接受函数及其参数。 您正在使用接受更具体策略的重载。

async(f, args...)相当于async(std::launch::async | std::launch::deferred, f, args...) ,其中两个标志的存在将其留给实现关于函数是否简单地从当前调用堆栈解耦(延迟执行第一个非定时等待函数;这称为惰性求值 ),或者实际上是多线程的。

通过仅提供 std::launch::async , 您正在使用的调用确保该函数在其自己的线程中明确执行,从而避免阻塞调用线程的任何工作。

当然,这两种变体仍然完全不同于直接简单地调用f(args...) ,这保证了立即评估。

According to the documentation, there is an overload that just takes the function and its arguments. You're using an overload that accepts a more specific policy.

async(f, args...) is equivalent to async(std::launch::async | std::launch::deferred, f, args...), where the presence of both flags leaves it up to the implementation as to whether the function is simply de-coupled from the current call stack (deferred to execution of the first non-timed wait function; this is called lazy evaluation), or actually multi-threaded.

The call you're using, by giving only std::launch::async, ensures that the function is definitely executed in its own thread, avoiding any work blocking the calling thread.

Both variants are still, of course, wholly dissimilar from simply invoking f(args...) directly, which guarantees immediate evaluation.

更多推荐