据我所知 async
在另一个线程/进程/核心中执行一个函数并且不会阻塞主线程,但总是这样吗?
我有以下代码:
async(launch::async,[]()
{
Sleep(1000);
puts("async");
});
puts("main");
它打印async main
,那么这是否意味着主线程一直等到async
完成?
如果我改为以下:
auto f = async(launch::async,[]() // add "auto f = "
{
Sleep(1000);
puts("async");
});
puts("main");
它打印 main async
。这看起来好像 main 不等待 async
完成。
最佳答案
As I know async executes a function in another thread/process/core and don't block main thread, but does it happens always?
std::async
仅当 std::launch::async
时才保证在单独的线程上执行作为第一个参数传递:
std::launch::async
: a new thread is launched to execute the task asynchronouslystd::launch::deferred
the task is executed on the calling thread the first time its result is requested (lazy evaluation)
默认启动策略是std::launch::async | std::launch::deferred
.
std::async
返回 std::future
. std::future
's destructor仅当从 std::async
返回 future 时才会阻塞:
these actions will not block for the shared state to become ready, except that it may block if all of the following are true: the shared state was created by a call to std::async, the shared state is not yet ready, and this was the last reference to the shared state
在您的第一个代码片段中,您创建了一个 右值表达式 立即销毁 - 因此
"async"
将在"main"
之前打印.异步匿名函数已创建并开始执行。
异步匿名函数被销毁。
main
执行被阻塞,直到函数完成。"async"
被打印出来了。
main
继续执行。-
"main"
已打印。
-
在您的第二个代码片段中,您创建了一个 左值表达式,其生命周期绑定(bind)到变量
f
.f
将在main
结束时销毁函数的范围 - 因此"main"
将在"async"
之前打印由于Delay(1000)
.异步匿名函数已创建并开始执行。
- 有一个
Delay(1000)
延迟"async"
不会立即被打印出来。
- 有一个
main
继续执行。-
"main"
已打印。
-
main
结束的范围。异步匿名函数被销毁。
main
执行被阻塞,直到函数完成。"async"
被打印出来了。
关于c++ - 异步是否总是在 C++ 中使用另一个线程/核心/进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42951452/