下面两个语句在执行方面有什么区别?
async([]() { ... });
thread([]() { ... }).detach();
最佳答案
std::async ([]() { ... }); // (1)
std::thread ([]() { ... }).detach (); // (2)
大多数情况下,当 std::async
被讨论时,首先注意到的是它被破坏了,这个名字暗示了当返回值不被接受时不成立的东西(分配给要在当前作用域结束时销毁的变量)。
在这种情况下,std::async
的中断 正是导致 (1)
和(2)
; 一个会阻止,另一个不会。
为什么 std::async
会在这个上下文中阻塞?
std::async
的返回值 是一个std::future
,它有一个必须在代码之前执行的阻塞析构函数继续。
在下面的示例中,g
直到 f
完成后才会执行,这仅仅是因为 (3)
未使用的返回值在相关声明中的所有工作完成之前,不能销毁。
std::async (f); // (3)
std::async (g); // (4)
std::thread (...).detach ()
的目的是什么?
当从 std::thread
分离时,我们只是在说; “我不关心这个线程句柄了,请执行该死的东西。”
继续与前一个示例类似(关于 std::async
),区别非常明显; f
和 g
将同时执行。
std::thread (f).detach ();
std::thread (g).detach ();
关于c++ - async([](){}) 和 thread([](){}).detach() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22242719/