SCOPE LOCKING

Ensures that locking is acquired when control enters a scope and released automatically when it leaves.

Also called: Synchronized Lock, Resource-Acquisition-Is_Initialization, Guard, Execute Around Object.


class LOCK
{
  public:
    virtual void acquire() = 0;
    virtual void release() = 0;
};
The abstract class LOCK must be subclassed by a concrete class implementing the acquire and release methods. A trivial example is a Null_Lock which provides empty implementations for both, and can be used when there is no need for locking.


class Guard 
{
  public:
    Guard( LOCK & lock )
      : lock_( lock ), owner_( false )
    {
      lock_->acquire();
      owner_ = true;
    }

    ~Guard()
    {
      if ( owner_ )
        lock_->release();
    }

  private:
    LOCK * lock_;
    bool   owner_;
    Guard( const Guard &);             // disable copying
    void opertaor= ( const Guard & );  // disable assignment
};
The class Guard is used to aqcuire a lock at the entrance of a scoped section, and to release is automatically when the destructor is invoked leaving the section.

{
  Guard guard( lock );
  // critical section
  // ...
  // lock automatically released
}
Marco Corvi - Page hosted by geocities.com.