c++ - std::async 在 c++11 和 linux 平台中不起作用

标签 c++ c++11 pthreads

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/

相关文章:

c++ - 互斥量锁定内存的哪一部分? (线程)

c++ - 扫描线多边形填充算法

c++ - 当未为其数据类型定义运算符 < 时,为什么 std::map 代码会编译?

单变量初始化的 C++ 风格

c++ - C++ 中的段错误在预分配缓冲区中创建的对象上调用虚方法

linux - 进程超过 RedHat Enterprise Linux 6 上的线程堆栈大小限制?

c++ - 线程池,C++

C++ ABI 问题列表

c++ - 这段c++代码在做什么?

c++11 - 用 std::unique_ptr/std::shared_ptr 确认线程安全