Mutexes and castles

Are two code examples 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 example: will the lock go out of scope after a copy of the return value has been made? This would be important if an object were returned that had many copy instructions.
  • Is locking required if you only return int? Or is it copying an int atomic operation?
+6
c ++ multithreading mutex poco-libraries
source share
2 answers

They are equivalent. Local residents do not go beyond the scope until the last line of their block is completed. Therefore, in this case, a copy of the return value is executed under lock protection.

+8
source share

If Poco ScopedLock works like Boost lock_guard, and PID assignment cannot throw an exception, the answer to the first question is yes. The purpose of this ScopedLock is to prevent deadlocks. You cannot forget to unlock mutexes even if exceptions are thrown. Do you need a lock even if you are "just reading some data"? Well, in this case (access to only one int) is a gray area (better not to do this), but in general you also block the mutex if you just read the data.

+3
source share

All Articles