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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

Tihu灌顶   2022-11-26 我要评论

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: 打包线程处理函数

  • 通过类模板 packaged_task 包装线程处理函数
  • 通过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;
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们