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...\n";
    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;
}

原文链接: https://www.cnblogs.com/findumars/p/10692641.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    c++ 如何获取多线程的返回值?(std::thread ,std::async)

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/293296

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 下午2:57
下一篇 2023年2月15日 下午3:00

相关推荐