信号量是最早出现的用来解决进程同步与互斥问题的机制,包括一个称为信号量的变量及对它进行的PV原语操作。
实际上 Windows 系统提供了 Semaphore 内核对象实现信号量及 PV 操作, 其 P 操作相当于 WaitForSingleObject(hSemaphore, INFINITE), V 操作相当于 ReleaseSemaphore(hSemaphore, 1, NULL), 以下代码利用 Event 内核对象与计数器模拟实现了 PV 操作:
class Signal { private: LONG m_nCount; HANDLE m_hEvent; public: Signal() { m_nCount = 0; m_hEvent = NULL; }; Signal(int nInit) { m_nCount = nInit; m_hEvent = NULL; }; ~Signal() { if (m_hEvent) CloseHandle(m_hEvent); }; BOOL pAction() { if (0 > InterlockedDecrement(&m_nCount)) { if (m_hEvent == NULL) m_hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); return (WAIT_OBJECT_0 == WaitForSingleObject(m_hEvent, INFINITE)); } return TRUE; }; BOOL vAction() { if (0 <= InterlockedIncrement(&m_nCount)) { if (m_hEvent) return PulseEvent(m_hEvent); } return TRUE; }; };
END