Can you use thread local variables inside a class or structure Can you use thread local variables inside a class or structure multithreading multithreading

Can you use thread local variables inside a class or structure


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 __thread keyword 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 new or malloc() is used. Either way, each thread receives a unique storage location for the variable and __thread is just not applicable in this case, hence the compiler error you get.


gcc imposes the following restrictions on the use of __thread:

The __thread specifier may be applied to any global, file-scoped static, function-scoped static, or static data member of a class. It may not be applied to block-scoped automatic or non-static data member.

The __thread modifier is supported by multiple compiler. It is not inconceivable that the exact restrictions vary somewhat from compiler to compiler.


You should change __thread int tl; to thread_local static int tl;