C C C 11初探多執行緒

2021-08-14 16:24:10 字數 2838 閱讀 2279

c++11 併發指南系列(256code)

本系列很多參考該專欄

之前在linux下,一直使用 pthread 使用多執行緒變成。c++11 新標準中引入了五個標頭檔案來支援多執行緒程式設計,他們分別是, , , 和 。這樣,你就可以在語言層面編寫多執行緒程式了,直接的好處就是**的可移植性得到了提高。

:該頭文主要宣告了兩個類,std::atomic 和 std::atomic_flag,另外還宣告了一套 c 風格的原子型別和與 c 相容的原子操作的函式。

:該標頭檔案主要宣告了 std::thread 類,另外 std::this_thread 命名空間也在該標頭檔案中。

:該標頭檔案主要宣告了與互斥量(mutex)相關的類,包括 std::mutex 系列類,std::lock_guard,std::unique_lock以及其他的型別和函式。

:該標頭檔案主要宣告了與條件變數相關的類,包括 std::condition_variable 和 std::condition_variable_any。

:該標頭檔案主要宣告了 std::promise,std::package_task 兩個 provider 類,以及 std::future 和 std::shared_future 兩個 future 類,另外還有一些與之相關的型別和函式,std::async() 函式就宣告在此標頭檔案中。

本片主要介紹 std::thread類的使用。

std::thread類的宣告:

namespace std ;

}

std::this_thread命名空間裡的相關函式:

namespace std         

}

乙個例子:

#include #include #include void f1() 

}void f2(int& n)

}int main()

輸出如下:

thread::id of a non-executing thread

t1 : false

thread 140649719494400

t2 : true

thread 140649719494400

thread 140649719494400

thread 140649719494400

thread 140649719494400

140649719494400

t1 : true

t2 : false

final value of n is 5

joinable() 可以檢查執行緒是否可被 join。由預設建構函式建立的執行緒是不能被 join 的。執行緒被建立後在尚未join()之前,都是可以被 join 的。

成員函式get_id()和std::this_thread::get_id()用於獲取執行緒id,返回乙個std::thread::id物件。

成員函式 swap() 和 非成員swap()可用於交換兩個執行緒物件所代表的底層控制代碼。

#include #include #include void f1() 

}void f2(int& n)

}int main()

輸出如下:

t1: 140219993110272

t2: 140219984717568

t1: 140219984717568

t2: 140219993110272

t1: 140219993110272

t2: 140219984717568

成員函式 detach(): 將子執行緒與父執行緒分離,使子執行緒執單獨執行。執行緒資源**由系統完成,父執行緒不用再呼叫 join(),確切的說,不能呼叫join(),會造成異常,類似的 join() 也不能呼叫兩次。

#include #include #include void f1() 

}int main()

輸出:

t1: true

thread 140507549996800

t1: false

native_handle() :返回原生控制代碼(std::thread 的實現和作業系統相關,因此該函式返回與 std::thread 具體實現相關的執行緒控制代碼,例如在符合 posix 標準的平台下(如 unix/linux)是 pthread 庫)

hardware_concurrency() [static]: 檢測硬體併發特性,返回當前平台的執行緒實現所支援的執行緒併發數目,但返回值僅僅只作為系統提示(hint)。

#include #include int main()

sleep_until(): 執行緒休眠至某個指定的時刻(time point),該執行緒才被重新喚醒。

sleep_for(): 執行緒休眠某個指定的時間片(time span),該執行緒才被重新喚醒。

yield(): 當前執行緒放棄執行,作業系統排程另一線程繼續執行。

#include #include #include void littlerest(std::chrono::microseconds sec)  while (std::chrono::high_resolution_clock::now() < end);

std::cout << count << std::endl;

}int main()

輸出:1478

C C C 11積累記錄

c,c c 11的大部分內容相同,但在使用時需要注意區分一些細節。一 cpp檔案中含有引用引數的函式如下 status destroytriplet triplet t 但是標準 c 不支援引用引數,使用.c檔案需要轉換為 status destroytriplet triplet t 在 資料結構...

多執行緒初探

多執行緒程式設計一直沒做過,沒有這方面的需求 自己先學習一下多執行緒的基礎,弄點小例子試驗.建立執行緒有兩種方法 繼承thread類和實現runnable介面。color red 一 繼承 thread 類,覆蓋方法 run color 在建立的 thread 類的子類中重寫 run 加入執行緒所要...

C C C 多執行緒入門例項講解

題目 三個執行緒,兩個執行緒分別生成乙個隨機數,第三個執行緒計算和。思路 熟悉c 多執行緒的用法以及互斥鎖的使用,此例好像不用加鎖。設定微秒級別的隨機數種子。不然產生的兩個隨機數一樣。include include include include include using namespace st...