Scoped Locks : Synchronization policies in c++

Mutex Synchronization can be explained as :

getLock(mutex);
… // this is critical section
releaseLock(mutex);

However, if the code within a critical section has conditional return statements or conditionally throws exceptions then care must be taken to release the mutex lock at all exit points of the critical section.
getLock(mutex);

if (…) {
releaseLock(mutex);
return;
}

To avoid adding releaseLock at every exit point , use following pattern:

class ScopedLock {
public:
ScopedLock(Mutex & mutex) //This is copy Constructor
: m_mutex(mutex)
{
getLock(m_mutex);
}
~ScopedLock() {
releaseLock(m_mutex);
}
protected:
Mutex & m_mutex;
};
void foo()
{
ScopedLock scopedLock(mutex);
….
}

This is confined to mutual exclusion (and occasionally readers-writer locks)

C++ C C# Health concepts Leetcode Programming Data Streucture