C++异步线程

std :: async无法异步工作(std::async doesn't work asynchronously)

I have the following very simple code:

void TestSleep()
{
    std::cout << "TestSleep " << std::endl;
    sleep(10);
    std::cout << "TestSleep Ok" << std::endl;

}

void TestAsync()
{
    std::cout << "TestAsync" << std::endl;
    std::async(std::launch::async, TestSleep);
    std::cout << "TestAsync ok!!!" << std::endl;

}

int main()
{
    TestAsync();
    return 0;
}

Since I use std::launch::async I expect that TestSleep() will be run asynchronously and I will have the following output:

TestAsync
TestAsync ok!!!
TestSleep 
TestSleep Ok

But really I have the output for synchronous run:

TestAsync
TestSleep 
TestSleep Ok
TestAsync ok!!!

Could you explain why and how to make TestSleep call really asynchronously.

解决方案

From this std::async reference notes section

If the std::future obtained from std::async is not moved from or bound to a reference, the destructor of the std::future will block at the end of the full expression until the asynchronous operation completes, essentially making code ... synchronous

This is what happens here. Since you don't store the future that std::async returns, it will be destructed at the end of the expression (which is the std::async call) and that will block until the thread finishes.

If you do e.g.

auto f = std::async(...);

then the destruction of f at the end of TestAsync will block, and the text "TestAsync ok!!!" should be printed before "TestSleep Ok".

我有以下非常简单的代码:


 

  void TestSleep()
 {
 std: :cout<< " TestSleep"<< std :: endl; 
 sleep(10); 
 std :: cout<< " TestSleep Ok"<< std :: endl; 
 
} 
 
 void TestAsync()
 {
 std :: cout<< " TestAsync"<< std :: endl; 
 std :: async(std :: launch :: async,TestSleep); 
 std :: cout<< " TestAsync好!!!" << std :: endl; 
 
} 
 
 int main()
 {
 TestAsync(); 
返回0; 
} 
  


 

因为我使用 std :: launch :: async 我希望 TestSleep()将异步运行,并且我将获得以下输出:


 

  TestAsync 
 TestAsync好!!! 
 TestSleep 
 TestSleep好
  


 

但实际上我有同步运行的输出:


 

  TestAsync 
 TestSleep 
 TestSleep好吧
 TestAsync好!!! 
  


 

您能否解释为什么以及如何制作 TestSleep 真的是异步调用。

来自此 std :: async 参考注释部分



< blockquote> 

如果从 std :: async 获得的 std :: future 从引用或绑定到引用, std :: future 的析构函数将在完整表达式的末尾阻塞,直到异步操作完成,从本质上使代码...同步



 

这就是这里发生的情况。由于您不存储 std :: async 返回的未来,因此它将在表达式末尾(即 std: :async 调用),它将阻塞直到线程结束。


 

如果您这样做,例如


 

  auto f = std :: async(...); 
  


 

然后销毁 f TestAsync 的行将被阻止,并且文本" TestAsync ok !!!" 应该在" TestSleep OK" 。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值