![](/img/trans.png)
[英]Can you initialize a thread in a class which references a function inside that class?
[英]Can you use thread local variables inside a class or structure
像這樣。
struct some_struct
{
// Other fields
.....
__thread int tl;
}
我正在嘗試這樣做,但編譯器給了我這個錯誤。
./cv.h:16:2: error: '__thread' is only allowed on variable declarations
__thread int tl;
在 C 和 C++ 中,線程局部存儲適用於靜態變量或僅具有外部鏈接的變量。
局部(自動)變量通常在堆棧上創建,因此特定於執行代碼的線程,但全局和靜態變量在所有線程之間共享,因為它們駐留在數據或 BSS 段中。 TLS 提供了一種機制來使這些全局變量局部於線程,這就是__thread
關鍵字所實現的 - 它指示編譯器在每個線程中創建變量的單獨副本,同時在詞法上它仍然是全局或靜態的(例如,它可以由同一執行線程內調用的不同函數訪問)。
非靜態類成員和結構成員放置在分配對象(類或結構)的位置 - 如果聲明了自動變量則放在堆棧上,或者如果使用new
或malloc()
則放在堆上。 無論哪種方式,每個線程都會收到一個唯一的變量存儲位置,而__thread
在這種情況下不適用,因此會出現編譯器錯誤。
gcc
對__thread
的使用施加了以下限制:
__thread
說明符可以應用於類的任何全局、文件范圍靜態、函數范圍靜態或靜態數據成員。 它可能不適用於塊范圍的自動或非靜態數據成員。
__thread
修飾符受多個編譯器支持。 不同編譯器的確切限制有所不同,這並非不可想象。
你應該改變__thread int tl;
到thread_local static int tl;
C11 標准第 6.7.1 節第 2 段
最多可以在聲明中的聲明說明符中給出一個存儲類說明符,除了 _Thread_local 可以與 static 或 extern 一起出現。120)
C11 標准第 6.7.1 節第 3 段
在具有塊作用域的對象的聲明中,如果聲明說明符包含 _Thread_local,則它們還應包含 static 或 extern。 如果 _Thread_local 出現在對象的任何聲明中,則它應出現在該對象的每個聲明中。
根據舊的 Petzold 書“Programming Windows”(第 1241 頁),您可以使用關鍵字將變量標記為線程本地:__declspec(線程)。 例如: __declspec (thread) int iGlobal = 1;
我懷疑這可以在課堂上完成。 您也可以將變量設為靜態。 [編輯] 剛剛意識到您可能沒有在 Windows 上運行...所以我想對於需要 Windows 答案的任何人來說,這可能是相關的。
這樣寫:
template <class T> struct S {
thread_local static int tlm;
};
template <> thread_local int S<float>::tlm = 0; // "static" does not appear here
如https://en.cppreference.com/w/cpp/language/storage_duration 中所述
對於 C 這沒有多大意義, static
(= 全局)成員只是 C++ 的一個特性。 因此,新的 C11 標准(引入_Thread_local
)不允許這樣做。 這些野獸基本上在任何地方都是允許的,並且允許具有靜態存儲持續時間的變量。
對於 C++,這在類內部類似於static
成員是有意義的,但如果 C++11 允許這樣做,我不知道。
您可以將thread_local
用於 C++ 中類或結構的static
成員。
struct some_struct
{
// Other fields
.....
thread_local static int tl;
}
這應該沒問題。 所以some_struct::tl
在不同的線程中可以有不同的值。 如果要定義它,則必須再次添加thread_local
:
thread_local int some_struct::tl = 10;
您還可以將結構本身指定為線程本地。 例如;
#include <pthread.h>
thread_local struct gl_i_t{
int a;
int b;
}GL_i_t;
然后你可以在線程內使用 GL_i_t 變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.