C++线程中packaged_tack

时间:2021-04-09 17:11:50

packaged_tack<>函数是一个你可以先定义好任务的类型,但是不想马上启动。函数可以在你想要启动任务是启动,你只需要调用你声明的函数就可以。

#include <future>
#include <iostream>
#include <exception>
#include <thread>
#include <chrono>
using namespace std; double compute(int x, int y)
{cout << x << y << endl;
cout << "this Thread Start: " << this_thread::get_id() << endl; try{
for (int i = ; i < ; ++i)
this_thread::sleep_for(chrono::milliseconds());
}
catch (const exception& e)
{
cerr << "EXCEPTION: " << e.what() << endl;
}
return x > y;
} int main()
{
try{
packaged_task<double(int, int)> task(compute);//定义一个task,并不要马上开始,什么时候开始由你什么时候调用task();
future<double> f = task.get_future();//用来获取线程结果
thread t([]{
try{
cout << "Main Thread Start: " << this_thread::get_id() << endl;
for (int i = ; i < ; ++i)
{
this_thread::sleep_for(chrono::milliseconds());
cout.put('@').flush();
}
}
catch (const exception& e)
{
cerr << "EXCEPTION: " << e.what() << endl;
} });
this_thread::sleep_for(chrono::milliseconds());
task(, );//当task调用时其线程才开始,所以它必须在f.get()前调用,否则线程一直等待
double res = f.get(); cout << res << endl;
}
catch (const exception& e)
{
cerr << "EXCEPTION: " << e.what() << endl;
} system("pause");
return ;
}