以下两个语句在执行方面有何区别?
async([]() { ... });
需要翻译的内容并没有给出明确的指示,如果您有其他需要翻译的内容,请提供更具体的指示,我将竭尽所能为您服务。
thread([]() { ... }).detach();
以下两个语句在执行方面有何区别?
async([]() { ... });
thread([]() { ... }).detach();
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
的例子,区别显然:函数 f
和 g
将同时执行。
std::thread (f).detach ();
std::thread (g).detach ();
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();
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();
}