zoukankan      html  css  js  c++  java
  • c++ 如何获取多线程的返回值?(std::thread ,std::async)

    //简单的 c++11 线程,简单方便,成员函数随便调用,非成员函数也一样,如需要获取返回时,请自行使用条件变量
        std::thread run([&](){
            //执行一些耗时的操作
            return 0;
        });
        run.detach();
        auto run=std::async([&](){
            return this->执行一些耗时的操作成员函数();
        });
        run.get();
        auto run=std::async(std::launch::async,[&](){
            return this->执行一些耗时的操作成员函数();
        });
        run.get();
    auto future = std::async(std::launch::deferred, function, arg1, arg2);
     
    // some time later, possibly in another thread:
    future.get(); // calls the function with the arguments
    // Console.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #include <stdlib.h>
    #include <iostream>
    #include <thread>   //线程库
    #include <future>
    #include <mutex>
    #include<numeric>
    
    std::mutex g_display_mutex;
    
    void foo()
    {
        std::thread::id this_id = std::this_thread::get_id();
    
        g_display_mutex.lock();
        std::cout << "thread " << this_id << " sleeping...
    ";
        g_display_mutex.unlock();
    
        std::this_thread::sleep_for(std::chrono::seconds(0));
    }
    
    void threadTest()
    {
        std::thread t1(foo);
        std::thread t2(foo);
        t1.join();
        t2.join();
    }
    
    int sum(int &x, int &y)
    {
        std::cout << std::hex << std::this_thread::get_id() << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
        return x + y;
    }
    
    int sums(int x, int y,int z)
    {
        std::cout << std::hex << std::this_thread::get_id() << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
        return x + y + z;
    }
    
    
    int main()
    {
        
        int x = 3;
        int y = 4;
        std::future<int> fu = std::async(sums, 3, 4,5);
        //std::future<int> fu = std::async(sum,std::ref(x),std::ref(y));
        std::cout << fu.get() << std::endl;
    
        //获取当前计算机线程数量
        std::cout << std::thread::hardware_concurrency() << std::endl;
        //获取当前线程ID
        std::cout << std::hex <<std::this_thread::get_id() << std::endl;
        system("pause");
        return 0;
    }
    
  • 相关阅读:
    (转载)C#控件缩写规范
    ToString()格式和用法大全,C#实现保留两位小数的方法
    C#数字前面如何补0
    (转载)C#语言开发规范
    (转载)C#:Enum、Int和String的互相转换,枚举转换
    [踩坑系列]URLEncode 中对 空格的编码有 “+”和“%20”两种
    [IDEA]IDEA设置注释模板
    [Mybatis]Mybatis 常用标签及功能整理
    [设计模式]静态代理
    记一次java电话面试
  • 原文地址:https://www.cnblogs.com/findumars/p/10692641.html
Copyright © 2011-2022 走看看