線程(std::thread)
看std::thread
的簡介時候,能夠知道std::thread
的Member types
- id //thread id
- native_handle_type //Native handle type
Member functions
- (constructor) //construct thread
- (destructor) //Thread destructor
- operator= //Move-assign thread
- get_id //Get thread id
- joinable //Check if joinable(可結合的)稍后解釋可結合的意思
- join //join thread
- detach //Detach thread
- swap //swap threads
- native_handle //Get native handle
- hardware concurrency[static] // detect hardware concurrency
non-member overloads
- swap(thread) // Swap threads(function)
因為類數據成員我們看注釋都可以讀懂相關的含義,所以直接上相關的成員函數
先是初始化
我們在初始化直接使用
std::thread name (function)
這樣的格式即可,如果我們不用后面的小括號的話,只進行線程的命名,那么就是進行了默認初始化
thread線程常用函數:
joinable():
joinabe成員函數的作用在c++官方文檔中是返回線程是否是可結合的。
可結合的意思就是,一個線程是否能夠被執行Join或者是detch操作,因為相同的線程不能被join兩次,也不能join完再進行detach,同理也不可以被detach兩次,所以joinable函數就是判斷是否能進行可結合。
在c++的官方文檔中列出了不能被joinable的情況。
在c++的官方文檔中列出了不能被joinable的情況。
- 是被默認構造的(即沒有小括號的構造語句)std::thread name;
- 執行過move操作
- 執行過join或者detach
join():
join在從c++官方文檔的介紹中,我們可以知道,join是用來進行同步的一個工具,當我們在主進程中使用join了一個子進程,那么我們主進程就要等待這個子進程運行完畢,並且回收子進程的資源后,再執行主進程的程序。
detach():
我們先從detach的字面意思進行理解下,detach指的是分離,脫離的意思,那么我們引申過來,在線程中的話,detach的意思就是將主線程和子線程進行分離,主線程是不會再等待子線程。
那么這個時候會有一個疑問,就是主線程結束的時候,進程也就結束,那么是不是表示子線程也是結束。結果不是,子線程的輸出只是不進行顯示,它還是會運行完,再被回收。
如果刪除掉了join試圖運行時,發現它是按照不同順序來進行的,但是運行到最后會出現abort() has been called
,搜查了相關資料發現,join以后會表示這個線程可以destroy了,那么在子線程結束后會進行相關資源的回收,但是如何沒有join或者detach,就會導致不會產生標記,在最后整個進程結束時,該回收的資源沒有回收,就會產生錯誤。
實際使用的example:
#include <iostream> #include <thread> #include <mutex> using namespace std; thread thRev; thread thSend; /// 互斥鎖 用於線程之間同步數據 std::mutex mtx; /// 接收線程或讀線程 void funRev() { while(true) { if (mtx.try_lock()) { /// 操作部分 mtx.unlock(); } } } /// 發送線程或寫線程 void funSend() { while(true) { if (mtx.try_lock()) { /// 操作部分 mtx.unlock(); } } } int main() { // 創建線程 thRev = thread(funRev); thSend = thread(funSend); thRev.join(); thSend.join(); return 0; }
參考: