A version of this page is also available for
A semaphore is an interprocess synchronization object that maintains a count between zero and a maximum value.
The object state is signaled when its count is greater than zero, and nonsignaled when its count is zero.
A semaphore is used as a counting resource gate, limiting the use of a resource by counting threads as they pass in and out of the gate.
Each time a waiting thread is released because of the signaled state of a semaphore, the count of a semaphore is decremented.
Use the CreateSemaphore function to create a named or unnamed semaphore object.
The handle returned by CreateSemaphore can be used in any function that requires a handle to the semaphore object.
Any thread of a calling process can specify the semaphore handle in a call to a wait function.
Use the ReleaseSemaphore function to increment a semaphore count. The count can never be less than zero or greater than the initial count specified by the lInitialCount parameter.
Before a thread uses the resource, it specifies the semaphore handle in a call to a wait function. When the wait function returns, it decrements the semaphore count, and the waiting thread runs.
When a thread finishes using a resource, the thread calls ReleaseSemaphore to increment the semaphore count.
ReleaseSemaphore can also be used during initialization of an application.
The application can create a semaphore with an initial count of zero. This sets the semaphore to nonsignaled and blocks all threads from accessing the protected resource.
When the application finishes initialization, it uses ReleaseSemaphore to increase the count to its maximum value and permit normal access to the protected resource.
Semaphores can be used across processes or within a single process.
Multiple processes can have handles of the same semaphore object. This provides synchronization between objects. Always use the CreateSemaphore function, because Windows Mobile does not implement the OpenSemaphore function.
Use the CloseHandle function to close the handle. The system closes the handle when the process ends. When you close the last handle for a semaphore, the semaphore object is destroyed.