mutexes and locks
Asked Answered
N

2

6

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?
Necktie answered 17/11, 2009 at 20:39 Comment(0)
C
8

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.

Contravention answered 17/11, 2009 at 20:47 Comment(0)
S
3

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.

Schleicher answered 17/11, 2009 at 20:45 Comment(4)
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.Necktie
As far as I can tell, first the return value is "constructed" then all automatic objects are destructed.Schleicher
I just realized that if a function returns a local variable, it has to copy it before destructing it. Doh.Necktie
+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.Entity

© 2022 - 2024 — McMap. All rights reserved.