async([](){})和thread([](){}).detach()有什么区别?

12

以下两个语句在执行方面有何区别?

async([]() { ... });

需要翻译的内容并没有给出明确的指示,如果您有其他需要翻译的内容,请提供更具体的指示,我将竭尽所能为您服务。
thread([]() { ... }).detach();
3个回答

22
std::async  ([]() { ... });            // (1)
std::thread ([]() { ... }).detach ();  // (2)

通常讨论std::async时,首先指出的是它被破坏了。当返回值不受尊重(即分配给一个变量以在当前范围结束时销毁)时,该名称意味着其所表示的内容不存在。

在这种情况下,std::async破碎性恰好会导致(1)(2)之间存在巨大的差异; 其中一个将阻塞,而另一个则不会。


为什么在这种情况下std::async会阻塞?

std::async返回值是一个std::future,它具有必须在代码继续执行之前执行的阻塞析构函数。

在下面的示例中,(3)的未使用返回值无法在相关语句中的所有工作完成之前被销毁,因此g直到f完成才会执行。

std::async (f); // (3)
std::async (g); // (4)

std::thread(...).detach() 的目的是什么?

当从一个 std::thread 中分离时,我们简单地表示:“我不再关心这个线程句柄,请执行它。”

继续上一个关于 std::async 的例子,区别显然:函数 fg 将同时执行。

std::thread (f).detach ();
std::thread (g).detach ();

如果一个对象有一个阻塞析构函数,请直接执行。谢谢,这些措辞很容易记住。 - Cevik
浏览了所有评论后,我真的没有发现std::Async的任何用处,它看起来就像普通的线程执行,主线程等待异步返回。 - ShivaPrasad Gadapa

3
我知道你已经得到了一个很好的答案,但如果我们稍微改变一下你的问题,会发生一些有趣的事情。
想象一下,如果你保留了async返回的未来对象,并且没有分离线程,而是像这样创建了一个变量: 异步代码
auto fut=std::async([]() { ... });
std::thread th([]() { ... });

现在,您已经了解了这两个概念的区别所在。
th.join()//you're here until the thread function returns

fut.wait_for(std::chrono::seconds(1)); //wait for 1 sec then continue.

Thread(线程)在加入时是全有或全无的,而Async(异步)则可以被检查并且您可以做其他事情。

wait_for实际上返回一个状态,所以您可以像这样执行操作。

 int numOfDots = 0;
 //While not ready after waiting 1 sec do some stuff and then check again
 while(fut.wait_for(std::chrono::seconds(1)) !=  std::future_status::ready)
 {
    (numOfDots++)%=20; 
    //Print status to the user you're still working on it.
    std::cout << "Working on it" <<std::string(numOfDots,'.')<<"\r"<<std::flush();
 }
 std::cout << "Thanks for waiting!\nHere's your answer: " << fut.get() <<std::endl(); 

2

async 返回一个 future 对象,而 detach 不会返回。所有 detach 所做的就是允许执行继续独立进行。为了实现与 async 类似的效果,您需要使用 join。例如:

{
    std::async(std::launch::async, []{ f(); });
    std::async(std::launch::async, []{ g(); });  // does not run until f() completes
}
{
    thread1.join();
    thread2.join();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接