c++多线程怎么创建具有返回值的线程处理函数

本文介绍了C++中使用async和thread进行线程处理的方法。async的launch::async方式会立即创建线程执行函数,而launch::deferred方式则延迟到调用get或wait时才执行。thread通过packaged_task包装函数或成员函数,创建线程并获取返回值。
摘要由CSDN通过智能技术生成

1.使用async来处理:

第一步:使用async启动一个异步任务创建线程,返回类型为一个future对象

第二步:使用对应future的对象接收async的返回值,之后通过get函数获取future里面的内容

async有两种线程处理方法:
1.使用launch::asnyc方式:则创建线程,并执行线程处理函数。
#include<iostream>
#include<thread>
#include<future>
using namespace std;
int text1(int a)
{
    cout << "id:" << this_thread::get_id()<<" start" << endl;
    cout << "id:" << this_thread::get_id() << " end" << endl;
    return a + 100;
}
int main()
{
    future<int> f=async(launch::async,text1, 10);
    cout << "主线程" << endl;
    cout << f.get() << endl;
    return 0;
}

运行效果如下:

 

2.使用launch::deferred方式:线程处理函数延迟,直到遇到wait和get方法时,才会执行,本质是没有创建线程的。
#include<iostream>
#include<thread>
#include<future>
using namespace std;
int text1(int a)
{
    cout << "id:" << this_thread::get_id()<<" start" << endl;
    cout << "id:" << this_thread::get_id() << " end" << endl;
    return a + 100;
}
int main()
{
    future<int> f=async(launch::deferred,text1, 10);
    cout << "主线程" << endl;
    //cout << f.get() << endl;或者是f.wait()也可以创建线程
    return 0;
}

运行效果如下:

 

如果把cout << f.get() << endl;的注释删掉,则运行效果如下:

 

2.使用thread来处理:

第一步:通过类模板package_task来包装线程处理函数

第二步:通过package_task对象调用get_future方法,获得future对象,之后再调用get方法即可。

#include<iostream>
#include<thread>
#include<future>
using namespace std;
int text1(int a)
{
    cout << "id:" << this_thread::get_id()<<" start" << endl;
    cout << "id:" << this_thread::get_id() << " end" << endl;
    return a + 100;
}
void test1()//打包普通函数
{
    //这里的模板类型是返回值为int,参数为一个int的函数类型,注意这里的函数类型要和你要作为线程处理函数的类型一致
    packaged_task<int(int)> t(text1);
    //注意,这里的thread的构造函数的参数是packaged_task类的引用,所以需要使用ref转换为右值引用,接着传入参数
    thread t1(ref(t), 10);
    t1.join();
    cout << t.get_future().get() << endl;
}
class person
{
public:
    int print(int a)
    {
        cout << "id:" << this_thread::get_id() << " start" << endl;
        cout << "id:" << this_thread::get_id() << " end" << endl;
        return a + 10;
    }
};
void test2()//打包类的成员函数
{
    person p;//创建对象
    //这里要通过函数适配器bind来绑定类的成员函数,第一个参数是类的成员函数,第二个参数是指定类的对象,第三个参数是根据成员函数的参数的个数,来设置占位符
    packaged_task<int(int)> tt(bind(&person::print,&p,placeholders::_1));
    thread t2(ref(tt),10);//同样转为右值引用后传入参数
    t2.join();
    cout<<tt.get_future().get() << endl;
}
int main()
{
    test2();
    return 0;
}

test1普通函数运行效果如下:

 

test2类的成员函数运行效果如下:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码商道

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值