我有这个代码:
#include <future>
#include <thread>
int main()
{
std::promise<void> p;
p.set_value();
p.get_future().get();
return 0;
}
用 gcc
编译后抛出 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
奇怪的是,在 创建 promise 之前添加零秒 sleep ,防止了异常:
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,结果相同。为什么会这样?
最佳答案
此错误来自您的编译。应该是:
g++ -o foo foo.cpp -std=c++11 -pthread
<thread>
图书馆需要这个特殊标志 -pthread
但你提供了-lpthread
.前者使用完整的线程支持编译您的翻译单元。后者只是链接库,没有定义需要的宏和需要的工具。
关于大肠杆菌:
关于c++ - std::promise<void> 抛出未知错误,除非调用 sleep ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48381486/