Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Advanced
Aug 4, 2009

Using the Guard Mechanism in Multi-Threaded Applications

Using the guard mechanism in multi-threaded applications instead of explicit Lock and Unlock instructions can save you from a number of undesirable synchronization problems.

Developers writing multi-threaded applications often fall into the trap of acquiring a lock—and then failing to release it—which can lead to random blackouts. Even when the lock does get released, it's sometimes held longer than necessary, because of the need to invoke the locking and unlocking mechanisms explicitly. This type of problem potentially leads to sluggish application performance.

You can eliminate such problems by implementing a guard mechanism. Essentially, the guard is a wrapper over the underlying lock that implicitly locks the scope when the Guard object is constructed, and unlocks the scope when the Guard object gets destroyed.

Here's an example implementation of a guard that makes use of a CRITICAL_SECTION as the underlying synchronization primitive:

class CLock
{
public:
   virtual int release()=0;
   virtual int acquire()=0;
   CLock(){};
   virtual ~CLock(){};
};

class CCriticalSectionLock : public CLock
{
public:
   CCriticalSectionLock()
   {
      InitializeCriticalSection(&m_CriticalSection);
   }
   virtual ~CCriticalSectionLock()
   {
      DeleteCriticalSection(&m_CriticalSection);
   }
   int acquire()
   {
      EnterCriticalSection(&m_CriticalSection);
      return 0;
   }
   int release()
   {
      LeaveCriticalSection(&m_CriticalSection);
      return -1;
   }
private:
   CRITICAL_SECTION m_CriticalSection;
};

class CLockGuard
{
public:
   CLockGuard(CLock &lock):m_Lock(lock)
   {
      acquire();
   }
   int acquire()
   {
      m_Owner = m_Lock.acquire();
      return m_Owner;
   }
   int release()
   {
      if (m_Owner == 0)
      {
         m_Owner = -1;
         m_Lock.release();
      }
      return -1;
   }
   ~CLockGuard()
   {
      release();
   }
private:
   CLock &m_Lock;
   int m_Owner; //0 means lock is acquired & -1 means not acquired
};

You can use the preceding classes in a program as follows:

//Declare the lock object at some common (global) scope
CCriticalSectionLock g_lock;

CThread::MethodRequiringLocking()
{
   ...
   // Code segments that need not be synchronized.
   ...

   // Code segment that requires synchronization
   {
      CLockGuard LockGurad(g_lock);

      //Perform synchronization sensitive operations
   }

   ...
   // Segments that need not be synchronized.
   ...
}
Senthil Sivasubramanian
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap