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. 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 (i.e. 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
. 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. Is there something I'm missing?
I've tried this using both g++ and clang with the same results. Specifically, when I run the code at the top, the following is output to 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