Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use thread local variables inside a class or structure

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; 
like image 529
pythonic Avatar asked Jun 12 '12 14:06

pythonic


People also ask

What is ThreadLocal variables and where they are stored?

Thread local can be considered as a scope of access like session scope or request scope. In thread local, you can set any object and this object will be local and global to the specific thread which is accessing this object. Java ThreadLocal class provides thread-local variables.

How do ThreadLocal variables work?

The local variables of a function are unique to each thread that runs the function. However, the static and global variables are shared by all threads in the process. With thread local storage (TLS), you can provide unique data for each thread that the process can access using a global index.

What is ThreadLocal variable in Java?

The Java ThreadLocal class enables you to create variables that can only be read and written by the same thread. Thus, even if two threads are executing the same code, and the code has a reference to the same ThreadLocal variable, the two threads cannot see each other's ThreadLocal variables.


Video Answer


1 Answers

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.

like image 90
Hristo Iliev Avatar answered Oct 08 '22 23:10

Hristo Iliev