我有這個代碼片段:
#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"
為什么我的程式意外結束,如何解決?
uj5u.com熱心網友回復:
您正在將打包的任務移動到執行緒中,然后嘗試從不再具有任何狀態的移動任務中獲取未來物件。對我來說,這會引發例外: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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/496626.html
