日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

C++多線程之帶返回值的線程處理函數(shù)解讀_C 語言

作者:Tihu灌頂 ? 更新時(shí)間: 2022-12-23 編程語言

No.1 async:創(chuàng)建執(zhí)行線程

1.1 帶返回值的普通線程函數(shù)

第一步: 采用async:?jiǎn)?dòng)一個(gè)異步任務(wù),(創(chuàng)建線程,并且執(zhí)行線程處理函數(shù)),返回值future對(duì)象

第二步: 通過future對(duì)象中的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方法的時(shí)候才會(huì)執(zhí)行,本質(zhì)是沒有創(chuàng)建子線程的

No.2 thread:創(chuàng)建線程

2.1 packaged_task: 打包線程處理函數(shù)

  • 通過類模板 packaged_task 包裝線程處理函數(shù)
  • 通過packaged_task的對(duì)象調(diào)用get_future獲取future對(duì)象,再通過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ù)適配器進(jìn)行封裝
	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表達(dá)式
	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存儲(chǔ)函數(shù)需要返回的值

第二步: 通過get_future()獲取future對(duì)象,再通過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;
}

原文鏈接:https://blog.csdn.net/m0_50597798/article/details/126710056

欄目分類
最近更新