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

2022-11-25 10:09:36

目录No.1async:创建执行线程1.1带返回值的普通线程函数1.2带返回值的类成员函数1.3async的其他参数No.2thread:创建线程2.1packaged_task:打包线程...

目录
No.1 async:创建执行线程
1.1 带返回值的普通线程函数
1.2 带返回值的类成员函数
1.3 async的其他参数
No.2 thread:创建线程
2.1 packaged_task:打包线程处理函数
2.2 promise :获取线程处理函数“返回值”

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存储函javascript数需要返回的值

第二步: 通过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;
}

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