Should I protect operations with primitive types with mutexes to ensure thread safety in C ++?

What is the best approach to ensure thread safety for fairly simple operations?

Consider a couple of functions:

void setVal(int val)
{
    this->_val = val;
}

int getVal() {
     return this->_val;
}

Since even assignments of primitive types are not guaranteed to be atomic, should I change every getter and setter in the program as follows 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;
}
+3
source share
4 answers

Do you use _valin multiple threads? If not, then no, you do not need to synchronize access to it.

, , , (, std::atomic<T> ++ 0x, , ).

+6

, . , , , - , .

+1

32- x86 32- , 4- , . 64- 64- 8- , . SPARC POWER .

++ , , .

+1
int getVal() { 
     this->_mutex.lock(); 
     int result = this->_val; 
     this->_mutex.unlock(); 
     return result; 
}

? , this->_val result, , , , , . , , . .

void setVal(int val)          
{          
    this->_mutex.lock();          
    this->_val = val;          
    this->_mutex.unlock();          
} 

Similarly, what are you buying? If you call setVal(-5)and setVal(17)of the separate streams at the same time, what value should be after completion? You encountered some problems to make sure that the first one to start will also be the first, but how to do this to get the “right” value?

-3
source

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


All Articles