Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mutexes and locks

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?
like image 465
StackedCrooked Avatar asked Nov 17 '09 20:11

StackedCrooked


1 Answers

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.

like image 144
David Joyner Avatar answered Sep 28 '22 09:09

David Joyner