c++ 11 packaged_task do do do do do do do do not:table tagret:thread退出且无输出

发布于 2025-02-11 02:31:28 字数 775 浏览 3 评论 0原文

我有这个代码片段:

#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秒钟,然后结束。我看不到我的打包函数执行。它没有打印“加入\ n”“等待\ n”

为什么我的程序意外结束,如何修复?

I've this code snippet:

#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;
}

It only printed

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

then hang for about 2 seconds, and ends. I don't see my packaged_task function execute. It didn't print "after join\n" and "after wait\n"

Why my program ended unexpectedly, how to fix?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

错爱 2025-02-18 02:31:29

您正在将包装的任务移至线程中,然后尝试从不再具有任何状态的移动任务中获取未来对象。对我来说,这给我带来了例外: https://godbolt.org/z/gh534dkac

丢弃了'std :: fune_error'

的实例后终止调用

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

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

what a href =“ https://godbolt.org/z/xhzkxh96k” rel =“ nofollow noreferrer”> https://godbolt.org/z/xhzkxh966k

You're moving the packaged task into the thread and then trying to get the future object from the moved-from task which no longer has any state. For me this throws an exception: https://godbolt.org/z/Gh534dKac

terminate called after throwing an instance of 'std::future_error'

what(): std::future_error: No associated state

You need to instead get the future from the task before moving it into the thread:

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

https://godbolt.org/z/xhzKxh96K

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文