c++ - 为什么 `std::promise::set_value`从主线程调用时会抛出错误?

标签 c++ multithreading c++-standard-library

当我运行以下代码时,

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

相关文章:

c++ - 在 C++ 中将 vector 中的对象方法应用于第二个 vector 中的对象

c++ - Josuttis 书中的 PersonSortCriterion(第一版与第二版)

C++ 生成不重复的随机数。输出屏幕只是空白,光标闪烁

C++ 意外的多线程行为

java - 为什么我在尝试读取 DataInputStream 时收到 EOFException?

python - Python Bottle 应用程序中的类实例,是否在线程/进程之间共享?

c++ - MacPorts Clang 3.1 缺少标准库安装?

c++ - 为什么我们应该为 initializer_list 的情况重载转发构造函数?

c++ - 重载赋值运算符总线错误

C# 通用行为与 C++ 模板