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
更好的替代方法.使用 <chrono>
header 和它与 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;
}
与您发布的其余代码段一起,这应该可以按预期工作。
关于c++ - std::async 在 c++11 和 linux 平台中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53426527/