我有这个代码:
#include <future>
#include <thread>
int main()
{
std::promise<void> p;
p.set_value();
p.get_future().get();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在用gcc它编译之后抛出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
Run Code Online (Sandbox Code Playgroud)
有什么奇怪的,在创建promise 之前添加零秒睡眠,可以防止异常:
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
$
Run Code Online (Sandbox Code Playgroud)
我尝试了gcc4.8.5和5.4.0,结果相同.为什么它表现得那样?