zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    HDU 1800 Flying to the Mars 字典树,STL中的map ,哈希树
    字典树 HDU 1075 What Are You Talking About
    字典树 HDU 1251 统计难题
    最小生成树prim算法 POJ2031
    POJ 1287 Networking 最小生成树
    次小生成树 POJ 2728
    最短路N题Tram SPFA
    poj2236 并查集
    POJ 1611并查集
    Number Sequence
  • 原文地址:https://www.cnblogs.com/zxllm/p/5383271.html
Copyright © 2011-2022 走看看