C 11 thread 使用類成員變數

2021-10-22 16:57:31 字數 1875 閱讀 7866

看到網上的例子大多是記錄如何呼叫乙個外部全域性函式介面,

不過,先說明下thread的用法,後續再說明如何使用物件的方式使用thread

返回乙個型別為 std::thread::id 的物件。請看下面例子:

#include

#include

#include

void

foo(

)int

main()

檢查當前的執行緒物件是否表示了乙個活動的執行執行緒,由預設建構函式建立的執行緒是不能被 join 的。另外,如果某個執行緒 已經執行完任務,但是沒有被 join 的話,該執行緒依然會被認為是乙個活動的執行執行緒,因此也是可以被 join 的。

**如下:

#include

#include

#include

void

foo(

)int

main()

join: join 執行緒,呼叫該函式會阻塞當前執行緒,直到由 *this 所標示的執行緒執行完畢 join 才返回。

#include

#include

#include

void

foo(

)void

bar(

)int

main()

將當前執行緒物件所代表的執行例項與該執行緒物件分離,使得執行緒的執行可以單獨進行。一旦執行緒執行完畢,它所分配的資源將會被釋放。

呼叫 detach 函式之後:

另外,如果出錯或者 joinable() == false,則會丟擲 std::system_error。

#include

#include

#include

void

independentthread()

void

threadcaller()

intmain()

#include

#include

#include

void

foo(

)void

bar(

)int

main()

執行結果如下:

thread 1 id:

1892

thread 2 id:

2584

after std:

:swap

(t1, t2)

:thread 1 id:

2584

thread 2 id:

1892

after t1.

swap

(t2)

:thread 1 id:

1892

thread 2 id:

2584

如果掉乙個類的成員函式,大概是這樣。

clientthread = std:

:thread

(&client:

:sendmessage,「message」)

;

std::thread 呼叫類的成員函式需要傳遞類的乙個物件指標作為引數:

#include

#include

class bar };

intmain()

如果是在類的成員函式中處理thread,傳入 this 即可,如:

std:

:thread spawn()

具體參考:

c 11 thread使用介紹

原因 c11裡面的thread用法,故在此進行梳理一下 概況 通過類內呼叫與跨類進行呼叫進行 分析。首先分析一下thread標頭檔案 explicit thread fn fx,args ax thread thread other noexcept bool joinable 判斷執行緒宣告週期是...

深入 C 11 thread 類的實現

雖然基本上也猜得到 c 11 thread的底層實現肯定是呼叫 crt 的 來實現的。但是還是好奇心想找到它的實現 我們從thread.join 找起 在 vc 2017 直接點找到 thread 標頭檔案 直接右鍵 轉到定義 include class thread inline void thr...

使用C 11 thread建立執行緒出現的問題總結

出現錯誤如下 1.c2672 std invoke 未找到匹配的過載函式 2.未能使函式模板 unknown type std invoke callable types noexcept 專用化原因是因為定義執行緒引數給錯了,如下 錯誤 如下 某標頭檔案執行緒宣告如下 class csocketh...