Should I protect operations on primitive types with mutexes for being thread-safe in C++?

后端 未结 4 1755
清酒与你
清酒与你 2021-01-20 15:20

What is the best approach to achieve thread-safety for rather simple operations?

Consider a pair of functions:

void setVal(int val)
{
    this->_         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-20 15:59

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

    What exactly are you hoping to accomplish with this? Sure, you've stopped this->_val from changing before you saved into result but it still may change before result is returned, -- or between the return and the assignment to whatever you assigned it -- or a microsecond later. Regardless of what you do, you are just going to get a snapshot of a moving target. Deal with it.

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

    Similarly, what is this buying you? If you call setVal(-5) and setVal(17) from separate threads at the same time, what value should be there after both complete? You've gone to some trouble to make sure that the first to start is also the first to finish, but how is that help to get the "right" value set?

提交回复
热议问题