Figure 2: PrioritySemaphore.h

#include<windows.h>

////////////////////////////////////////////////////////////////
//
// The class CPrioritySemaphore extends the functionality of a 
// Win32 semaphore by providing levels of priority when waiting 
// on the semaphore. The class has a non-virtual destructor and 
// should therefore not be subclassed.
//
class CPrioritySemaphore
{
public:

   // Default constructor. The semaphore is not valid until the
   // Create() member function has been called.
   CPrioritySemaphore();

   // The destructor closes all handles and dealloctes all memory.
   ~CPrioritySemaphore();

   // Allocates all memory and creates all synchronization 
   // objects
   BOOL Create(
       LONG lNumPriorityLevels, // number of priority levels
       LONG lInitialCount,      // initial count
       LONG lMaximalCount       // maximal count
       );

   // Waits for the priority semaphore to become signaled
   DWORD Wait(
      LONG lWaitPriority,
      DWORD dwMillisecondsTimeout = INFINITE
      );

   // Releases the semaphore
   BOOL Release(
      LONG lReleaseCount,    // amount to add to the current count
      LPLONG lpPreviousCount // memory location to receive previous 
                             // count
    );

   // Retrieve the number of threads currently waiting on a given 
   // priority level.
   int GetNumWaitingThreads(
      LONG lWaitPriority // priority level to check
      );

private:

   // Private helper functions
   // ========================
  
   // Closes handles and dealloctes memory
   void Cleanup();

   // Data members
   // ============

   // Array containing event handles and semaphore handle
   HANDLE* m_arrSemaphoreAndEvents;

   // Array of numbers of waiting threads
   volatile LONG* m_arrNumWaitingThreads;

   // Number of priority levels
   LONG m_lNumPriorityLevels;

   // Critical section to protect the priorities mechanism
   CRITICAL_SECTION m_critsecPriorityProtection;
};