Is return an atom, and should I use a temporary in getter for streaming security?

Do I need to use temporary here for thread safety?

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

I will tell you about disassembling a simple test function RAII

int test()
{
    RAIITest raii; //let say it a scoped lock
    return 3;
}


 {
     0x004013ce <_Z4testv>:    push  %ebp
     0x004013cf <_Z4testv+1>:  mov   %esp,%ebp
     0x004013d1 <_Z4testv+3>:  sub   $0x28,%esp
     return 3;
     0x004013d4 <_Z4testv+6>:  lea   -0x18(%ebp),%eax
     0x004013d7 <_Z4testv+9>:  mov   %eax,(%esp)
     0x004013da <_Z4testv+12>: call  0x4167a0 <_ZN8RAIITestD1Ev>  //here destructor is called
     0x004013df <_Z4testv+17>: mov   $0x3,%eax //here result is pushed onto the stack
 }
 0x004013e4 <_Z4testv+22>: leave 
 0x004013e5 <_Z4testv+23>: ret   

gcc / g ++ 3.4.5 compiler

+5
source share
4 answers

If access is this->_valsynchronized using this->_mutex, then you have no choice about how to write code at this time. You must read this->_valbefore unlocking the mutexes, and you need to unlock the mutexes before returning. To get this order of action, a variable is needed result.

lock_guard ( scoped_lock Boost), , . , ++ 0x:

int getVal() {
    std::lock_guard<std::mutex> lock(_mutex);
    return this->_val;
}   // lock is released by lock_guard destructor 
+5

, lock()/unlock(). , , .

+1

- . , , , return _val; .

, , - , , , , .

0
source

You can do this cleanly, your mutex is encapsulated in scoped_lock, which unlocks when destroyed:

 int getVal() {
       scoped_lock lockit(_mutex);
       return _val;
 }

And yes, you need to hold the lock until it returns.

0
source

All Articles