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)

Resolving technical problems:

Solve your technical problems instantly

We provide Remote Technical Support from Monday to Sunday, 7:00PM to 1:00 AM

Mail your problem details at writeulearn@gmail.com along with your mobile numberand we will give you a call for further details. We usually attend your problems within 60 minutes and solve it in maximum 2 days.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.