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

學無先后,達者為師

網站首頁 編程語言 正文

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

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

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;
}

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

欄目分類
最近更新