What is the best approach to achieve thread-safety for rather simple operations?
Consider a pair of functions:
void setVal(int val)
{
this->_val = val;
}
int getVal() {
return this->_val;
}
Since even assignments of primitive types aren’t guaranteed to be atomic, should I modify every getter and setter in the program in the following way to be thread-safe?
void setVal(int val)
{
this->_mutex.lock();
this->_val = val;
this->_mutex.unlock();
}
int getVal() {
this->_mutex.lock();
int result = this->_val;
this->_mutex.unlock();
return result;
}
Are you using
_valin multiple threads? If not, then no, you don’t need to synchronize access to it.If it is used from multiple threads, then yes, you need to synchronize access, either using a mutex or by using an atomic type (like
std::atomic<T>in C++0x, though other threading libraries have nonstandard atomic types as well).