I'm working on multi-threading function which defined as a member function and using a common variable of the object.
I'm thinking about two approaches :
1. global variable
static int var = 0;
class Object {
void specialOp { var++; }
}
2. static data member
class Object {
static int var = 0;
void specialOp { var++; }
}
I prefer the second option but when I looked on the internet I didn't find the implementation of static data member to know if I need to care of locks or if the complexity is higher than using in a global variable.
The static
keyword in C++ means different things depending on where it is used.
Class::variable
but in accordance to the access specifiers of the class (need to declare it in a cpp file as well)None of the able addresses multithreading though. To address multi-threading, you have a few options:
thread_local
. This means each thread gets its own version of the variable.std::atomic
or some other thread synchronization primitive like a std::mutex