C++基础-多线程并行计算

为了获得并行计算的结果,需要使用 packaged_task对任务进行打包,使用pt1.get_future().get() 来获取结果 

全部代码

//
// Created by Administrator on 2021/6/27.
//
#include<thread>
#include<iostream>
#include<future> //线程将来结果
#include<chrono> //时间
#include <mutex>

using namespace std;

mutex g_m;

int main()
{
    auto run = [=](int index)->int{ //只读
        lock_guard<mutex> lckg(g_m); //加锁
        cout <<this_thread::get_id << " " << index << endl; //获取线程id
        this_thread::sleep_for(chrono::seconds(10));
        return index * 1024;
    };
    packaged_task<int(int)> pt1(run);
    packaged_task<int(int)> pt2(run);   //创建两个任务包
    thread t1([&](){pt1(2);});
    thread t2([&](){pt2(3);}); //开启线程
    cout << pt1.get_future().get() << endl;
    cout << pt2.get_future().get() << endl; //获取结果

    t1.join();
    t2.join();
}
原文地址:https://www.cnblogs.com/my-love-is-python/p/14941809.html