Acquiring Mutex Ownership
If the order in which threads acquire a mutex are the same order in which ownership is granted, then first-in-first-out or FIFO ordering is being used. The
RWMutexLock class does not ensure FIFO ordering.
Different systems use different policies for granting mutex ownership. Some prioritize acquisition requests based on the priority of the thread; others can maintain FIFO ordering (unless the thread is interrupted for some reason, in which case its position in any internal queue can be changed).
If you require FIFO acquisition semantics regardless of a thread’s priority or any other factors, then use the
RWFIFOMutexLock class.
An
RWMutexLock is commonly used to protect data or resources by limiting access to one thread at a time. Access is typically controlled by requiring that a mutex be acquired prior to reading or manipulating the data or resource. Once the actual access is completed, the mutex should then be released.
Example 32 illustrates this concept by implementing a simple thread-safe queue class based on a linked list class from the Essential Tools Module.
Example 32 – Using a mutex to prevent interference between threads
#include <rw/sync/RWMutexLock.h>
#include <rw/tvslist.h>
template <class T>
class Queue {
private:
RWMutexLock mutex_;
RWTValSlist<T> list_;
public:
void enqueue(const T& t) {
mutex_.acquire();
list_.append(t);
mutex_.release();
}
T dequeue(void) {
mutex_.acquire();
T result = list_.removeFirst(t);
mutex_.release();
return result;
}
}
Using Mutexes discussed the disadvantages of explicitly coding the mutex acquisition and release, which was done in this example. If either linked-list member function or the copy constructor for the template parameter class throws an exception, the
Queue’s mutex is not released.