• 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;
    }
  • 相关阅读:
    观察者与被观察者
    Gson和阿里的JSON简单对比
    银行卡输入特效 4个加一空格
    Android 点击空白处蕴藏键盘
    Android覆盖安装及常遇到的问题
    Android view中的requestLayout和invalidate方法
    医药行业GSP注册流程
    如何快速查询视图
    反写规则超额控制
    预算管理的操作步骤
  • 原文地址:https://www.cnblogs.com/zxllm/p/5383271.html
Copyright © 2020-2023  润新知