【问题标题】:C++11 packaged_task doesn't work as expected: thread quits and no outputC++11 packaged_task 无法按预期工作:线程退出且无输出
【发布时间】:2022-06-27 23:31:30
【问题描述】:

我有这个代码 sn-p:

#include<future>
#include<iostream>
using namespace std;
int main() {
  cout << "---------" << endl;
  packaged_task<int(int, int)> task([](int a, int b){
    cout << "task thread\n";
    return a + b;
  });
  thread tpt(move(task), 3, 4);
  cout << "after thread creation\n";
  future<int> sum = task.get_future();
  cout << "before join\n";
  tpt.join();
  cout << "after join\n";
  sum.wait();
  cout << "after wait\n";
  cout << sum.get() << endl;
  return 0;
}

它只是打印出来的

---------
after thread creation
task thread

然后挂起大约 2 秒,然后结束。我没有看到我的 packaged_task 函数执行。它没有打印"after join\n""after wait\n"

为什么我的程序意外结束,如何解决?

【问题讨论】:

    标签: c++ multithreading future packaged-task


    【解决方案1】:

    您正在将打包的任务移动到线程中,然后尝试从不再具有任何状态的已移动任务中获取未来对象。对我来说,这会引发异常:https://godbolt.org/z/Gh534dKac

    在抛出 'std::future_error' 的实例后调用终止

    what(): std::future_error: 无关联状态

    您需要在将任务移入线程之前从任务中获取未来:

    ...
    future<int> sum = task.get_future();
    thread tpt(move(task), 3, 4);
    cout << "after thread creation\n";
    ...
    

    https://godbolt.org/z/xhzKxh96K

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多