thread 多線程詳解

win系統下 CPP多線程開發中thread是常用的多線程技術。微軟官方介紹地址thread

首先 看關鍵聲明,#include<thread>中

thread方法介紹
方法名 功能 說明
thread() 默認構造函數 構造一個空的,那麼如果需要控制哪個功能進行多線程,就需要用下面的 方法進行初始化
thread(_Fn&& _Fx, _Args&&... _Ax) 帶不定參數的構造函數

F

線程執行的應用程序中定義的函數。

A

傳遞給參數列表 F。

多線程的參數可以根據需求不定數量的傳參設定
thread(thread&& _Other) 用其他線程構造參數  
thread& operator=(thread&& _Other)  重載等號初始化對象  
thread(const thread&) = delete;    

thread::detach

分離 thread 對象關聯的線程

分離關聯線程。 操作系統將負責釋放終止線程的資源。

分離後的線程 無法再使用thread控制

thread::get_id 

返回關聯線程的唯一標識符 有個線程ID便可以控制這個線程

thread::hardware_concurrency 

靜態的。 返回硬件線程上下文的數目的估計值。
 
 

thread::join

阻塞,直到關聯的線程完成。 如果任務分塊執行 需要所有任務塊執行完後再進行下面的操作,則需要它
thread::joinable 指定關聯的線程是否可連接。  

thread::native_handle 

返回表示線程句柄的特殊類型的實現。
 
 

thread::swap 方法

交換與指定的 thread 對象的狀態。
 
 
     

演示例程:

	std::thread th1([]() {
		surf->detectAndCompute(a, Mat(), key1, c);
	}
	);
	std::thread th2([]() {
		surf->detectAndCompute(b, Mat(), key2, d);
	}
	);
	th1.join();
	th2.join();

如果代碼太長 上面的操作就有點不合適,也可以這麼寫 有無傳參兩種方式

void fun()
{
}
void fun1(int Val)
{	
}
std::thread th1(fun);
std::thread th2(fun1,val);
th1.join();
th2.join();

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章