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?
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:
-pthread
: http://coliru.stacked-crooked.com/a/a53bed6696bb8d83
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With