United States |
Previous | Contents | Index |
The Mutex package provides a way to synchronize access to user-defined objects. It consists of a single class, Mutex , that manages the creation, locking and unlocking of Mutex objects.
Construction of a Mutex object creates a recursive mutex that users can lock and unlock using the appropriate member functions or parameterized manipulators. A recursive mutex is a mutex that can be locked many times by the same thread without causing the thread to enter a deadlock state. To completely unlock this kind of mutex, the thread must unlock the mutex the same number of times that the thread locked the mutex. For more information see the Guide to DECthreads manual.
User-defined objects are not automatically thread safe. Users must supply synchronization for such objects if they are shared between threads. |
Provides a means whereby users can synchronize access to user-defined objects.
#include <mutex.hxx>#include <mutex.h>
class Mutex { public: Mutex(); ~Mutex(); void lock(); void unlock(); int trylock(); };
The synchronization process consists of locking and unlocking Mutex objects associated with user-defined objects. Digital recommends that users create a Mutex object for each user-defined object that needs to be synchronized between threads. Users are then responsible for locking and unlocking the Mutex object to coordinate access to the associated object.To do the locking and unlocking, you can use the lock and unlock member functions (see Example). Alternatively, if a user-defined object is derived from the istream or ostream classes, you can use the lock and unlock parameterized manipulators, where the parameter is the Mutex object (see the Global Declarations section in Chapter 4).
Mutex()
Constructs a Mutex object, in effect creating but not locking a recursive mutex.~Mutex()
Deletes a Mutex object.
void lock()
Locks a recursive mutex. If the mutex is locked by another thread, the current thread is blocked until the mutex becomes available.void unlock()
Unlocks a recursive mutex.int trylock()
Immediately returns to the caller a value of 0 if the mutex is already locked by another thread. Otherwise, this function locks the mutex and returns a value of 1.
#include <string.hxx> #include <mutex.hxx> . . . String string1; Mutex string1_lock; string1_lock.lock(); string1 = "Hello, "; string1 += "how are you?"; cout << string1; string1_lock.unlock(); |
This example synchronizes a sequence of operations on a String object, using the lock() and unlock() member functions.
Previous | Next | Contents | Index |