The Mutex Lock Primitive

In ThreadMentor, a mutex (or mutex lock, or simply lock) is defined in class Mutex with two methods: Lock() for acquiring the mutex and Unlock() for releasing the mutex.

The use of mutex locks is very easy. First, we need to declare a lock variable of type Mutex. Second, before entering the critical section that is protected by that lock, execute the Lock() method of that lock. Third, before exiting the critical section, execute the Unlock() method of the lock. In the following, we have a lock MyLock and use MyLock.Lock() and MyLock.Unlock() before entering and exiting the critical section.

Mutex  MyLock;


// critical section


For identification purpose, a mutex lock can have a name. One can supply a char array of characters as the argument of the declaration. For example, the following set the name of lock MyLock to Lock-with-a-Name:

Mutex*  MyLock;

MyLock = new Mutex("Lock-with-a-Name");


// critical section


If you do not provide a mutex lock a name, its name will be automatically set to No name. It is a good practice to assign names to locks because you will easily see which locks is owned by which thread with our visualization system.

Note because mutex locks are usually used by several threads, they are global data items. Moreover, Mutex locks should be initialized before their uses and it is a poor practice to re-initialize mutex locks in the middle of program execution. Moreover, mutex locks are not locked when they are created. Therefore, you have to lock the mutex lock if you wish to created locked mutex locks.