Mutual exclusion module. Provides procedures for creating and
operating on mutex locks for thread synchronization. Requires
--m2plus and links with pthreads.
TYPE Mutex; (* opaque mutex handle *)
PROCEDURE Create(): Mutex;
PROCEDURE Lock(m: Mutex);
PROCEDURE Unlock(m: Mutex);
PROCEDURE Destroy(m: Mutex);
Createallocates and initializes a new mutex.Lockacquires the mutex, blocking if it is already held.Unlockreleases the mutex.Destroyfrees the mutex resources.- Prefer the
LOCKstatement over manual Lock/Unlock calls, as LOCK guarantees the mutex is released even on exceptions.
MODULE MutexDemo;
FROM Mutex IMPORT Mutex, Create, Lock, Unlock, Destroy;
VAR
mu: Mutex;
shared: INTEGER;
PROCEDURE SafeIncrement;
BEGIN
Lock(mu);
shared := shared + 1;
Unlock(mu);
END SafeIncrement;
BEGIN
mu := Create();
shared := 0;
SafeIncrement();
Destroy(mu);
END MutexDemo.