C++多線程之帶返回值的線程處理函數(shù)解讀
更新時間:2022年11月25日 09:18:45 作者:Tihu灌頂
這篇文章主要介紹了C++多線程之帶返回值的線程處理函數(shù)解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
No.1 async:創(chuàng)建執(zhí)行線程
1.1 帶返回值的普通線程函數(shù)
第一步: 采用async:啟動一個異步任務,(創(chuàng)建線程,并且執(zhí)行線程處理函數(shù)),返回值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 帶返回值的類成員函數(shù)
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的其他參數(shù)
launch::async: 創(chuàng)建線程并且執(zhí)行線程處理函數(shù)launch::deferred:線程處理函數(shù)延遲到 我們調(diào)用wait和get方法的時候才會執(zhí)行,本質(zhì)是沒有創(chuàng)建子線程的
No.2 thread:創(chuàng)建線程
2.1 packaged_task: 打包線程處理函數(shù)
- 通過類模板 packaged_task 包裝線程處理函數(shù)
- 通過packaged_task的對象調(diào)用get_future獲取future對象,再通過get()方法得到子線程處理函數(shù)的返回值
void testPackaged_task()
{
//1. 打包普通函數(shù)
packaged_task<int(void)> taskOne(testThreadOne);//函數(shù)返回值加上參數(shù)類型
thread testOne(ref(taskOne));//需要使用ref轉(zhuǎn)換
testOne.join();
cout<<taskOne.get_future().get()<<endl;
//2. 打包類中的成員函數(shù)
//需要使用函數(shù)適配器進行封裝
Tihu tihu;
packaged_task<int(int)> taskTwo(bind(&Tihu::TihuThread,&tihu,placeholders::_1));//如果有參數(shù)需要使用占位符
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: 獲取線程處理函數(shù)“返回值”
第一步: promise類模板,通過調(diào)用set_value存儲函數(shù)需要返回的值
第二步: 通過get_future()獲取future對象,再通過get()方法獲取線程處理函數(shù)中的值
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;
}以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C語言如何利用輾轉(zhuǎn)相除法求最大公約數(shù)
這篇文章主要介紹了C語言如何利用輾轉(zhuǎn)相除法求最大公約數(shù)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08
Windows下VScode實現(xiàn)簡單回聲服務的方法
回聲服務端可以將客戶端傳來的信息,再原封不動地發(fā)送給客戶端,因而得名 epoch 服務。接下來通過本文給大家介紹Windows下VScode實現(xiàn)簡單回聲服務的方法,感興趣的朋友一起看看吧2021-08-08
C++ boost::asio編程-同步TCP詳解及實例代碼
這篇文章主要介紹了C++ boost::asio編程-同步TCP詳解及實例代碼的相關(guān)資料,需要的朋友可以參考下2016-11-11

