C++多线程之带返回值的线程处理函数

====================================================

No.1 async:创建执行线程

1.1 带返回值的普通线程函数

  • 第一步: 采用async:启动一个异步任务,(创建线程,并且执行线程处理函数),返回值future对象
  • 第二步: 通过future对象中的get()方法获取线程返回值
#include <iostream>
#include <thread>
#include <future>
using namespace std;
int testThreadOne()
{
	cout<<"testThreadOne_id:"<<this_thread::get_id()<<endl;
	return 1001;
}
void testAsync1()
{
	future<int> result = async(testThreadOne);
	cout<<result.get()<<endl;
}

1.2 带返回值的类成员函数

class Tihu
{
public:
	int TihuThread(int num)
	{
		cout<<"TihuThread_id"<<this_thread::get_id()<<endl;
		num *= 2;
		this_thread::sleep_for(2s);
		return num;
	}
}
void testAsync2()
	Tihu tihu;
	future<int> result = async(&Tihu::TihuThread,&tihu,1999);
	cout<<result.get()<<endl;
}

1.3 async的其他参数

  • launch::async: 创建线程并且执行线程处理函数
  • launch::deferred:线程处理函数延迟到 我们调用wait和get方法的时候才会执行,本质是没有创建子线程的

No.2 thread:创建线程

2.1 packaged_task:打包线程处理函数

    1. 通过类模板 packaged_task 包装线程处理函数
    1. 通过packaged_task的对象调用get_future获取future对象,再通过get()方法得到子线程处理函数的返回值
void testPackaged_task()
{	
	//1. 打包普通函数
	packaged_task<int(void)> taskOne(testThreadOne);//函数返回值加上参数类型
	thread testOne(ref(taskOne));//需要使用ref转换
	testOne.join();
	cout<<taskOne.get_future().get()<<endl;
	
	//2. 打包类中的成员函数
	//需要使用函数适配器进行封装
	Tihu tihu;
	packaged_task<int(int)> taskTwo(bind(&Tihu::TihuThread,&tihu,placeholders::_1));//如果有参数需要使用占位符
	thread testTwo(ref(taskTwo),20);
	testTwo.join();
	cout<<testTwo.get_future().get()<<endl;

	//3. 打包Lambda表达式
	packaged_task<int(int)> taskThree([](int num)
	{
		cout<<"thread_id:"<<this_thread::get_id()<<endl;
		num *= 10;
		return num;
	});
	thread testTwo(ref(taskThree),7);
	testTwo.join();
	cout<<testTwo.get_future().get()<<endl;
	
}

2.2 promise :获取线程处理函数“返回值”

  • 第一步: promise类模板,通过调用set_value存储函数需要返回的值
  • 第二步: 通过get_future()获取future对象,再通过get()方法获取线程处理函数中的值
void testPromiseThread(promise<int>& temp,int data)
{
	cout<<"testPromise"<<this_thread::get_id()<<endl;
	data *= 3;
	temp.set_value(data);
}
void testPromise()
{
	promise<int> temp;
	thread testp(testPromiseThread,ref(temp),19);
	testp.join();
	cout<<temp.get_future().get()<<endl;
}
int main()
{
	testAsync1();
	testAsync2();

	testPackaged_task();

	testPromise();
	
	return 0;
}

少年侠气,交结五都雄。肝胆洞,毛发耸。立谈中,死生同。一诺千斤重。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值