我怎么在这里滥用C++承诺和期货?

sdg*_*sdh 3 c++ future promise

这是我的代码,main.cpp:

#include <string>
#include <iostream>
#include <future>

int main() {
  using namespace std;

  auto p = promise<string>();

  p.set_value("Hello, world. ");

  auto f = p.get_future();

  cout << f.get() << endl;

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是错误:

./a.out    
terminate called after throwing an instance of 'std::system_error'              
  what():     
    Unknown error -1  [1]  

15195 abort (core dumped)  ./a.out
Run Code Online (Sandbox Code Playgroud)

我的编译器版本:

$ clang++ --version 
clang version 7.0.0-3 (tags/RELEASE_700/final)  
Target: x86_64-pc-linux-gnu 
Thread model: posix InstalledDir: /usr/bin
Run Code Online (Sandbox Code Playgroud)

我的编译命令:

$ clang++ ./main.cpp && ./a.out
Run Code Online (Sandbox Code Playgroud)

rod*_*igo 5

std::promise 是C++线程支持的一部分,即使您以非线程方式使用它.

所以你必须使用编译器选项-pthread:

clang++ -pthread main.cpp
Run Code Online (Sandbox Code Playgroud)

  • 这很有趣.怎么没有链接时间错误?另外,`-pthreads`标志是什么意思,它与`-lpthread`有什么不同? (3认同)