关于信号量,先看MSDN介绍:
Semaphore Objects
A semaphore object is a synchronization object that maintains a count between zero and a specified maximum value. The count is decremented each time a thread completes a wait for the semaphore object and incremented each time a thread releases the semaphore. When the count reaches zero, no more threads can successfully wait for the semaphore object state to become signaled. The state of a semaphore is set to signaled when its count is greater than zero, and nonsignaled when its count is zero.The semaphore object is useful in controlling a shared resource that can support a limited number of users. It acts as a gate that limits the number of threads sharing the resource to a specified maximum number.
For example, an application might place a limit on the number of windows that it creates. It uses a semaphore with a maximum count equal to the window limit, decrementing the count whenever a window is created and incrementing it whenever a window is closed.
即:信号量不同于临界区,信号量可以限定一定数量线程去执行关键代码,通过P(Wait)、V(Signal)操作来实现对当前可执行关键代码线程的管理。当信号量大于0时为有信号状态,等于0为无信号状态。线程对信号量操作可以影响信号量中的计数器,通过计数器可以控制线程进入关键代码的数量。
初始化
A thread uses the CreateSemaphore