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;
    }
  • 相关阅读:
    谷歌浏览器设置跨域失败
    Validation of viewstate MAC failed 解决办法--zt
    如何查看Oracle客户端版本及位数(Windows系统)(转)
    程序员集锦
    如何最快速地适应新的工作
    Oracle 03113
    Shell中字符串、数值的比较
    K8S客户端安装及使用
    kubectl的使用
    Helm 入门指南
  • 原文地址:https://www.cnblogs.com/zxllm/p/5383271.html
Copyright © 2011-2022 走看看