C++线程中packaged_tack

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 = 0; i < 5; ++i)
            this_thread::sleep_for(chrono::milliseconds(2000));
    }
    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 = 0; i < 10; ++i)
                {
                    this_thread::sleep_for(chrono::milliseconds(500));
                    cout.put('@').flush();
                }
            }
            catch (const exception& e)
            {
                cerr << "EXCEPTION: " << e.what() << endl;
            }


        });
        this_thread::sleep_for(chrono::milliseconds(5000));
        task(7, 5);//当task调用时其线程才开始,所以它必须在f.get()前调用,否则线程一直等待
        double res = f.get();
        
        cout << res << endl;
    }
    catch (const exception& e)
    {
        cerr << "EXCEPTION: " << e.what() << endl;
    }
    
    
    system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/zxllm/p/5383271.html