简体   繁体   中英

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. 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 . 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

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 ).

Note that -pthread affects the compilation as well as linkage stages. From man g++ :

-pthread
Adds support for multithreading with the pthreads library. This option sets flags for both the preprocessor and linker.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM