I have some private variables (say int a, int b, int c) inside my class. Due to some internal manipulations I need to set/get such variables in a thread safe way so I used some wrapping getters/setters and used a scoped mutex.
void setA(int a)
{
unique_lock<mutex> lock(opMutex);
this->a = a;
}
void getA(int a)
{
unique_lock<mutex> lock(opMutex);
return a;
}
void setB(int b)
{
unique_lock<mutex> lock(opMutex);
this->b = b;
}
void setC(int c)
{
unique_lock<mutex> lock(opMutex);
this->c = c;
}
My question is: is it possbile to avoid getter/setter methods (public variables) and keep thread safety on assign/read operations over such variables?
If you move your thread security synchronization code outside the getters setters, and bloat your code with boilerplate code locking mutexes everywhere, yes it's possible not to use getter and setters, but it would be really counter-productive.
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