Thread safety when accessing public variables

I have some private variables (e.g. int a, int b, int c) inside my class. Due to some internal manipulation, I need to set / get such variables in thread safe mode, so I used some wrapper getters / setters and used a mutex with scope.

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 possible to avoid getter / setter methods (public variables) and maintain thread safety when performing input / read operations on such variables?

+4
source share
4 answers

Boost has a similar boost :: atomic library, but it is not yet included in the standard AFAIK.

+3
source

If you move the thread's security synchronization code outside the getters installers and inflate your code by blocking the mutexes of the template code all over the world, yes, you may not use getters and setters, but it will be really counterproductive .

+4
source

If C ++ 11 is an option, consider std::atomic_store and std::atomic_load with atomic_int . However, you probably should still stay with getters / seters, so your decisions about how you manage your data (e.g. choosing between atoms and mutexes) will not affect class users, even if it is only you:)

If C ++ 11 is not an option, you can use one of the C ++ 98 compatible implementations of atomic operations. I have been using the proposed accelerator atomic library for some time, and there are other implementations moving around the Internet.

+3
source

You can use std::atomic<int> a, b, c;

PS. Ugh, I did not see the boost tag, so I thought you were talking in C ++ 11 ...

+2
source

Source: https://habr.com/ru/post/1447239/


All Articles