Important: |
---|
This is retired content. This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This content may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist. |
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 CreateSemaphorefunction to create a named or unnamed semaphore object.
The handle returned by CreateSemaphorecan 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 ReleaseSemaphorefunction to increment a semaphore count. The count can never be less than zero or greater than the initial count specified by the lInitialCountparameter.
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 ReleaseSemaphoreto increment the semaphore count.
ReleaseSemaphorecan 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 ReleaseSemaphoreto 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 CreateSemaphorefunction, because Windows Mobile does not implement the OpenSemaphorefunction.
Use the CloseHandlefunction 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.