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?
CodePudding user response:
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";
...