c++ 11 packaged_task do do do do do do do do not:table tagret:thread退出且无输出
我有这个代码片段:
#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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在将包装的任务移至线程中,然后尝试从不再具有任何状态的移动任务中获取未来对象。对我来说,这给我带来了例外: https://godbolt.org/z/gh534dkac
:
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
You need to instead get the future from the task before moving it into the thread:
https://godbolt.org/z/xhzKxh96K