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::Sc开发者_StackOverflow中文版opedLock<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?
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.
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.
精彩评论