Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local static variables for each thread

Tags:

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.

like image 913
Łukasz Przeniosło Avatar asked Jul 24 '15 11:07

Łukasz Przeniosło


People also ask

Are static variables shared between threads?

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.

Are static variables thread local?

Unlike local variables, static variables are not automatically thread confined.

Is local static variable thread-safe?

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.

Can we use static variable in multithreading?

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.


2 Answers

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.

like image 64
Pumkko Avatar answered Oct 07 '22 00:10

Pumkko


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.

like image 41
TartanLlama Avatar answered Oct 07 '22 00:10

TartanLlama