std :: promise< void>抛出未知错误,除非调用sleep [英] std::promise<void> throws Unknown error, unless calling 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.
关于大肠菌:
- 带有
-pthread
: http://coliru.stacked-crooked.com/a/a53bed6696bb8d83 - 不包含: http://coliru.stacked-crooked.com/a/fd972e1556f8c060
这篇关于std :: promise< void>抛出未知错误,除非调用sleep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!