当我运行以下代码时,
#include <future>
int main()
{
std::promise<int> p;
p.set_value(1);
return 0;
}
std::system_error
被抛出。但是,当我在另一个线程中设置 promise 的值时,#include <future>
#include <thread>
int main()
{
std::promise<int> p;
std::thread([&]{p.set_value(1);}).join();
return 0;
}
一切正常。据我了解std::promise
, 调用set_value
不应抛出异常,除非 promise 没有共享状态(即它已被移出)或已为其分配了值,即使那样它也会抛出 std::future_error
,而不是 std::system_error
.由于没有数据竞争或类似的事情,我是否调用 set_value
都无关紧要。从我创建 promise 的线程或另一个线程中。有什么我想念的吗?我已经使用 g++ 和 clang 进行了尝试,结果相同。具体来说,当我在顶部运行代码时,将以下内容输出到 stderr:
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
Aborted (core dumped)
这些命令用于编译顶部的代码,g++ main_thread.cpp -o main_thread -std=c++17 -g -Og
clang main_thread.cpp -o main_thread -std=c++17 -lstdc++
这些用于编译底部的代码:g++ separate_thread.cpp -o separate_thread -lpthread -std=c++17 -g -Og
clang separate_thread.cpp -o separate_thread -std=c++17 -lstdc++ -lpthread
最佳答案
std::promise
是 Thread Support Library 的一部分因此有理由认为它需要在您的编译器选项中启用线程支持(例如 -pthread
)。
请注意 -pthread
影响编译以及链接阶段。来自 man g++
:
-pthread
Adds support for multithreading with the pthreads library. This option sets flags for both the preprocessor and linker.
关于c++ - 为什么 `std::promise::set_value`从主线程调用时会抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66657016/