Threads Module User's Guide : PART II Concurrency Packages : Chapter 4 The Synchronization Package : The Synchronization Classes : The RWCriticalSection Class
The RWCriticalSection Class
The RWCriticalSection class is primarily intended for use in the Microsoft Win32 environment. In this environment, the class encapsulates the Win32 critical section mechanism, which is an efficient form of mutual exclusion based on a spin-lock. Spin-locks do not block a thread while waiting to acquire ownership of the critical section. A waiting thread spins in a polling loop until the section is released.
A critical section is more efficient than a mutex when little competition exists for a lock because the Win32 mutex acquisition requires kernel intervention even when the mutex is not currently owned by another thread.
In environments other than Win32, this class is implemented as a mutex. This allows a Win32 version of an application to realize the performance benefits of a critical section, but also allows that same code to be ported to platforms that do not have a critical section mechanism.
The RWSemaphore Class
The semaphore class uses a unique form of synchronization that might be considered a cross between mutual exclusion and condition synchronization. It implements a classic counting semaphore as developed by E. W. Dijkstra.
A semaphore is basically an integer counter, initialized to zero by default, that can be incremented and decremented. If a thread attempts to decrement the count when it is already zero, the thread is blocked until the decrement operation can succeed. Any thread can increment the semaphore, potentially releasing a thread that has been blocked trying to decrement it.
The decrement and increment operations are performed by the acquire() and release() methods, respectively. These functions correspond to Dijkstra’s P and V semaphore operations.
The RWSemaphore class has two versions of the acquire() function:
The first blocks indefinitely until the decrement operation can be performed.
The second accepts a time-limit for the wait, expressed as an unsigned long number of milliseconds.
When using an RWSemaphore instance that has been decremented to zero, you cannot assume that the order in which threads block trying to acquire is the same order that the threads unblock when the semaphore is released. Different systems can use different policies for processing semaphore acquisitions. Some can prioritize acquisition requests based on the priority of the thread; others can maintain a FIFO ordering (unless the thread is interrupted for some reason) in which case its position in any internal queue can be changed.