Like this.
struct some_struct
{
// Other fields
.....
__thread int tl;
}
I’m trying to do that but the compiler is giving me this error.
./cv.h:16:2: error: '__thread' is only allowed on variable declarations
__thread int tl;
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In C and C++, thread-local storage applies to static variables or to variables with external linkage only.
Local (automatic) variables are usually created on the stack and therefore are specific to the thread that executes the code, but global and static variables are shared among all threads since they reside in the data or BSS segment. TLS provides a mechanism to make those global variables local to the thread and that’s what the
__threadkeyword achieves – it instructs the compiler to create a separate copy of the variable in each thread while lexically it remains a global or static one (e.g., it can be accessed by different functions called within the same thread of execution).Non-static class members and structure members are placed where the object (class or structure) is allocated – either on the stack if an automatic variable is declared or on the heap if
newormalloc()is used. Either way, each thread receives a unique storage location for the variable and__threadis just not applicable in this case, hence the compiler error you get.