gpt4 book ai didi

c++ - std::promise 抛出未知错误,除非调用 sleep

转载 作者:可可西里 更新时间:2023-11-01 17:39:57 26 4
gpt4 key购买 nike

我有这个代码:

#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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com