Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

thread safety on public variables access

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?

like image 590
Gianluca Ghettini Avatar asked Dec 15 '22 17:12

Gianluca Ghettini


1 Answers

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.

like image 138
Stephane Rolland Avatar answered Dec 28 '22 08:12

Stephane Rolland