[英]Why does `std::promise::set_value` throw an error when invoked from the main thread?
When I run the following code,当我运行以下代码时,
#include <future>
int main()
{
std::promise<int> p;
p.set_value(1);
return 0;
}
std::system_error
is thrown.抛出
std::system_error
。 However, when I set the promise's value in another thread,但是,当我在另一个线程中设置承诺的值时,
#include <future>
#include <thread>
int main()
{
std::promise<int> p;
std::thread([&]{p.set_value(1);}).join();
return 0;
}
everything works fine.一切正常。 From what I understand about
std::promise
, calling set_value
shouldn't throw an exception unless the promise has no shared state (ie it's been moved from) or a value has already been assigned to it, and even then it would throw std::future_error
, not std::system_error
.根据我对
std::promise
std::future_error
了解,调用set_value
不应引发异常,除非 promise 没有共享 state (即它已被分配,甚至那时它已被分配)或将抛出一个值std::future_error
,而不是std::system_error
。 Since there's no data race or anything of that sort, it shouldn't matter whether I call set_value
from the thread in which I created the promise or in another thread.由于不存在数据竞争或任何类似的情况,因此无论我是从创建 promise 的线程还是在另一个线程中调用
set_value
都无关紧要。 Is there something I'm missing?有什么我想念的吗?
I've tried this using both g++ and clang with the same results.我已经使用g++和clang进行了尝试,结果相同。 Specifically, when I run the code at the top, the following is output to stderr :
具体来说,当我在顶部运行代码时,以下是 output 到stderr :
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
Aborted (core dumped)
These commands were used to compile the code at the top,这些命令用于编译顶部的代码,
g++ main_thread.cpp -o main_thread -std=c++17 -g -Og
clang main_thread.cpp -o main_thread -std=c++17 -lstdc++
and these were used to compile the code at the bottom:这些用于编译底部的代码:
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
is part of the Thread Support Library so it would stand to reason that it requires enabling thread support in your compiler options (eg -pthread
). std::promise
是线程支持库的一部分,因此它需要在编译器选项(例如-pthread
)中启用线程支持。
Note that -pthread
affects the compilation as well as linkage stages.请注意,
-pthread
会影响编译和链接阶段。 From man g++
:从
man g++
:
-pthread
-pthread
Adds support for multithreading with the pthreads library.使用 pthreads 库添加对多线程的支持。 This option sets flags for both the preprocessor and linker.
此选项为预处理器和 linker 设置标志。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.