DM1 Mutex

Purpose

A DM1 Mutex enables a section of code to be executed by one thread only at given a point in time. The Mutex is one of the fundamental thread synchronisation primitives supported by an Operating System.

An AutoMutex class is provided. This is a helper class designed to ensure that mutexes are released automatically when the program flow is broken because of an Exception being thrown. The destructor of an AutoMutex object automatically destroys the related Mutex object during stack unwinding.

Operations

There are only two operations supported by the Mutex object.

Lock - This blocks the calling thread until the Mutex is granted to the thread. Only one thread can own the Mutex at any point in time.

Unlock - Releases the Mutex and makes it available to other threads.

Implementation

On Win32, a DM1 Mutex is implemented as a CRITICAL_SECTION. Since DM1 does not support inter-process synchronisation, it does not require the greater flexibility and overhead of a Win32 Mutex.

On UNIX, a DM1 Mutex is implemented as a pthread_mutex object.

API

 
namespace dm1 { 
 
        class Mutex { 
 
        public: 
                /** 
                 * Creates a Mutex object. 
                 */ 
                explicit Mutex(); 
 
                /** 
                 * Destroys the Mutex object. 
                 */ 
                ~Mutex(); 
 
                /** 
                 * Acquires the Mutex lock. Calling thread is 
                 * blocked until the Mutex lock is granted. 
                 * Recursive calls are not supported. 
                 */ 
                void lock(); 
 
                /** 
                 * Unlocks the Mutex object. Caller must hold the  
                 * lock before calling unlock. 
                 */ 
                void unlock(); 
        }; 
 
        class AutoMutex { 
        public: 
                explicit AutoMutex(Mutex *mutex) ; 
                ~AutoMutex() ; 
                void lock() ; 
                void unlock() ; 
        }; 
} 

Copyright © 2002-2004 by Dibyendu Majumdar