Home > other >  Why does a single-threaded example of std::promise-std::future throw?
Why does a single-threaded example of std::promise-std::future throw?

Time:09-27

The following code throws std::system_error on recent g , clang compilers and I do not know why. MSVC seems to work.

I was under the impression multi-threaded context is not necessary for promise and future to work.

#include <future>
 
int main() {
    std::promise<int> p;
    std::future<int> f = p.get_future();
 
    p.set_value(1); //throws std::system_error
    return f.get();
}

Godbolt

Stacktrace on my machine:

#0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
#1  0x00007ffff7c38537 in __GI_abort () at abort.c:79
#2  0x00007ffff7e8c7ec in ?? () from /lib/x86_64-linux-gnu/libstdc  .so.6
#3  0x00007ffff7e97966 in ?? () from /lib/x86_64-linux-gnu/libstdc  .so.6
#4  0x00007ffff7e979d1 in std::terminate() () from /lib/x86_64-linux-gnu/libstdc  .so.6
#5  0x00007ffff7e97c65 in __cxa_throw () from /lib/x86_64-linux-gnu/libstdc  .so.6
#6  0x00007ffff7e8f458 in std::__throw_system_error(int) () from /lib/x86_64-linux-gnu/libstdc  .so.6
#7  0x0000555555556fce in void std::call_once<void (std::__future_base::_State_baseV2::*)(std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>*, bool*), std::__future_base::_State_baseV2*, std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>*, bool*>(std::once_flag&, void (std::__future_base::_State_baseV2::*&&)(std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>*, bool*), std::__future_base::_State_baseV2*&&, std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>*&&, bool*&&) ()
#8  0x00005555555569ae in std::__future_base::_State_baseV2::_M_set_result(std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>, bool) ()
#9  0x0000555555557417 in std::promise<int>::set_value(int&&) ()
#10 0x0000555555556346 in main ()

I fail to see how I am using std::promise::set_value incorrectly - p is valid and not set yet. Can anyone enlighten me please?

It works with clang -stdlib=libc so the issue is somewhere in libstdc , am I running into undefined behaviour or a bug?

CodePudding user response:

If I remember correctly, std::future depends on thread. So, you would need to link against -pthread.

Godbolt (with -pthread compiler option) https://godbolt.org/z/hPTMKqMjr

  • Related