Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::promise<void> throws Unknown error, unless calling sleep

Tags:

c++

gcc

c++11

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?

like image 457
Tomasz Maciejewski Avatar asked Jan 22 '18 12:01

Tomasz Maciejewski


1 Answers

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:

  • with -pthread: http://coliru.stacked-crooked.com/a/a53bed6696bb8d83
  • without: http://coliru.stacked-crooked.com/a/fd972e1556f8c060
like image 136
YSC Avatar answered Oct 23 '22 08:10

YSC