Lets say I have a class that after initialization creates a thread and runs a method in it, within it declares a static variable:
void method() { static int var = 0; var++; }
If I create more objects of the class, for example 3, then the method will be called 3 times in 3 different threads. After that var
will equal 3. How to accomplish the functionality, where each thread has its own static var
that is independent of others. I would appreciate all help.
Static variables are indeed shared between threads, but the changes made in one thread may not be visible to another thread immediately, making it seem like there are two copies of the variable.
Unlike local variables, static variables are not automatically thread confined.
Using a local static variable makes the program not thread-safe in the same way that a global variable (when not protected by locks) is not thread-safe.
Static variable is a shared resource, which can be used to exchange some information among different threads. And we need to be careful while accessing such a shared resource. Hence, we need to make sure that the access to static variables in multi-threaded environment is synchronized. This is a correct statement.
You can use the thread_local
keyword which indicates that the object has a thread storage duration. You can use it like that :
static thread_local int V;
If you want more information about storage class specifiers, you can check CppReference.
This is what the thread_local
storage class specifier is for:
void method() { thread_local int var = 0; var++; }
This means that each thread will have its own version of var
which will be initialized on the first run through that function and destroyed on thread exit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With