Linux C++多線程編程學習筆記

1. thread header

#include <thread>

2. 構造函數原型

default 		 (1)	 thread() noexcept;
initialization   (2)	 template <class Fn, class... Args>
					 	 explicit thread (Fn&& fn, Args&&... args);
copy [deleted]   (3)	 thread (const thread&) = delete;
move			 (4)   	 thread (thread&& x) noexcept;

2.1 參數說明

Fn: 函數指針、成員函數指針、函數對象,如果函數有返回值,將被忽略。
args: 調用Fn函數時傳遞的參數,如果Fn是指向成員函數,則第一個參數應該傳遞該成員函數所屬的對象的指針或引用

3. 創建thread對象

thread t_empty;	// 調用默認構造函數,不代表任何可執行的線程

4. 用一個函數初始化thread

#include <iostream>
#include <thread>


using namespace std;

void threadFunc()
{
    cout << "Welcome to Multithreading" << endl;
}

int main( )
{
         std::thread funcTest1(threadFunc);
         return 0;
}

運行結果:

Starting /home/rootroot/Learn/C++/MultiThread/multiThread/slamtest…

terminate called without an active exception

The program has unexpectedly finished.

/home/rootroot/Learn/C++/MultiThread/multiThread/slamtest crashed

運行出錯,因爲funcTest1線程沒有在main函數結束前結束。

要解決此問題,可以使用 join() 函數解決。
該函數僅僅在對應線程執行結束後纔會返回。

int main( )
{
         std::thread funcTest1(threadFunc);
         funcTest1.join(); // 線程結束後纔會返回
         return 0;
}

join() 返回後,該線程變爲 ** not joinable** ,
當線程由默認構造函數構建 或者 move/賦值給另一個線程 或者 join() or detach()成員函數被調用,在這三種情況下,此線程是不可 join() 的。

參考:

https://www.tutorialcup.com/cplusplus/multithreading.htm
http://www.cplusplus.com/reference/thread/thread/

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