std :: promise< void>抛出未知错误,除非调用sleep [英] std::promise<void> throws Unknown error, unless calling sleep

查看:57
本文介绍了std :: promise< void>抛出未知错误,除非调用sleep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

#include <future>
#include <thread>

int main()
{
    std::promise<void> p;
    p.set_value();
    p.get_future().get();

    return 0;
}

然后用 gcc 编译后,它会抛出 std :: system_error :

And after compiling it with gcc it throws std::system_error:

$ g++ -o foo foo.cpp -std=c++11 -lpthread
$ ./foo
terminate called after throwing an instance of 'std::system_error'
  what():  Unknown error -1

奇怪的是,在创建承诺之前,先添加零秒睡眠 ,以防止出现异常情况

What is weird, adding zero-second sleep before creating the promise, prevents the exception:

int main()
{
    std::this_thread::sleep_for(std::chrono::milliseconds(0));
    std::promise<void> p;
    p.set_value();
    p.get_future().get();

    return 0;
}

$ g++ -o foo foo.cpp -std=c++11 -lpthread
$ ./foo
$ 

我尝试了 gcc 4.8.5和5.4.0,结果相同.为什么会这样呢?

I tried gcc 4.8.5 and 5.4.0, same results. Why does it behave like that?

推荐答案

此错误来自您的编译.应该是:

This error comes from your compilation. It should be:

 g++ -o foo foo.cpp -std=c++11 -pthread

< thread> 库需要此特殊标志 -pthread ,但是您提供了 -lpthread .前者使用全线程支持来编译您的翻译单元.后者仅链接库,而没有定义所需的宏和所需的工具.

The <thread> library needs this special flag -pthread but you provided -lpthread. The former compile your translation unit with the full thread support. The later only links the library, without defining the needed macros and needed tools.

关于大肠菌:

这篇关于std :: promise&lt; void&gt;抛出未知错误,除非调用sleep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆