【问题标题】:std::async is not working in c++11, linux platformstd::async 在 c++11、linux 平台中不起作用
【发布时间】:2018-11-22 08:18:02
【问题描述】:
bool tf()
{
    sleep(5000);
    return true;
}

int main()
{
    std::future<bool> bb = std::async(std::launch::async, tf);
    bool b = false;
    while(1)
    {   
        if(b == true) break;

        b = bb.get();
    }   

    return 0;
}

为什么不工作? 我打算在 5 秒后终止程序。但是,该程序正在冻结。

【问题讨论】:

  • sleep 以秒为单位获取参数。所以你的程序进入休眠状态500 秒。可能你的意思是usleep
  • 检查你的假设:man 3 sleep
  • 顺便说一句:bb.get() 将阻塞你的主线程,直到未来完成或毁掉。循环调用这个方法是没有意义的。

标签: c++ c++11 pthreads


【解决方案1】:

有一个比直接调用全局sleep 更好的替代方法。将&lt;chrono&gt; 标头及其提供的字符串文字与std::this_thread::sleep_for 一起使用。这不太容易出错,例如

#include <chrono>

// Bring the literals into the scope:
using namespace std::chrono_literals;

bool tf()
{
   std::this_thread::sleep_for(5s);
   //                          ^^ Awesome! How readable is this?!

   return true;
}

与您发布的其他 sn-p 一起,这应该可以按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2021-08-16
    相关资源
    最近更新 更多