views:

286

answers:

2

Are the two code samples below equivalent?

Poco::ProcessHandle::PID ProcessRunner::processId() const
{
    Poco::ProcessHandle::PID pid = 0;
    mMutex.lock();
    pid = mPID;
    mMutex.unlock();
    return pid;
}

,

Poco::ProcessHandle::PID ProcessRunner::processId() const
{
    Poco::ScopedLock<Poco::Mutex> lock(mMutex);
    return mPID;
}
  • In the second sample: will the lock go out of scope after the return value copy has been made? This would matter if an object was returned that had many instructions for copying.
  • Is a lock necessary if you are only going to return an int value? Or is the copying of the int an atomic operation?
+3  A: 

If Poco's ScopedLock works anything like Boost's lock_guard and the PID assignment cannot throw an exception, the answer to the first question is yes. The purpose of this ScopedLock is to prevent deadlocks. You can't forget to unlock the mutex even in case of exceptions getting thrown. Do you need locking even if you "only read some data"? Well, in this case (accessing one int only) is kind of a grey zone (better don't do it) but in general you also lock the mutex if you just read data.

sellibitze
I'm more concerned about the atomicity of the operations. Which happens first in code sample 2: the copy of the return value or the destruction of the lock? If it this not the first one, then it is buggy code.
StackedCrooked
As far as I can tell, first the return value is "constructed" then all automatic objects are destructed.
sellibitze
I just realized that if a function returns a local variable, it has to copy it before destructing it. Doh.
StackedCrooked
+1 for "and the PID assignment cannot throw an exception". If the PID assignment CAN throw an exception, the second example would still properly unlock the mutex while the first one would leave the mutex locked.
ChrisInEdmonton
+7  A: 

They are equivalent. Locals don't go out of scope until after the last line of their block has been executed. So in this case, the return value copy is made under the protection of the lock.

David Joyner