9

I have this code:

#include <future>
#include <thread>

int main()
{
    std::promise<void> p;
    p.set_value();
    p.get_future().get();

    return 0;
}

And after compiling it with gcc it throws std::system_error:

$ g++ -o foo foo.cpp -std=c++11 -lpthread
$ ./foo
terminate called after throwing an instance of 'std::system_error'
  what():  Unknown error -1

What is weird, adding zero-second sleep before creating the promise, prevents the exception:

int main()
{
    std::this_thread::sleep_for(std::chrono::milliseconds(0));
    std::promise<void> p;
    p.set_value();
    p.get_future().get();

    return 0;
}

$ g++ -o foo foo.cpp -std=c++11 -lpthread
$ ./foo
$ 

I tried gcc 4.8.5 and 5.4.0, same results. Why does it behave like that?

YSC
  • 38,212
  • 9
  • 96
  • 149

1 Answers1

10

This error comes from your compilation. It should be:

 g++ -o foo foo.cpp -std=c++11 -pthread

The <thread> library needs this special flag -pthread but you provided -lpthread. The former compile your translation unit with the full thread support. The later only links the library, without defining the needed macros and needed tools.

On coliru:

YSC
  • 38,212
  • 9
  • 96
  • 149
  • @infinitezero it might be due to my first version which was unperfect (was it worth a downvote though, who knows?). – YSC Jan 22 '18 at 13:26