Microsoft Windows CE 3.0  

Semaphore Objects

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 interprocess synchronization object that maintains a count between zero and some maximum value. The object's state is set to 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 decreased by one.

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-object handle in a call to one of the wait functions.

Use the ReleaseSemaphorefunction to increment a semaphore count by a specified amount. The count can never be less than zero or greater than the initial count specified by the CreateSemaphore lInitialCountparameter.

Typically, an application uses a semaphore to limit the number of threads using a resource. Before a thread uses the resource, it specifies the semaphore handle in a call to one of the wait functions. When the wait function returns it decreases the semaphore count by one and the waiting thread is released to continue its execution. When a thread finishes using a resource, it calls ReleaseSemaphoreto increase the semaphore count by one.

ReleaseSemaphoremay also be used during intialization of an application. The application can create a semaphore with an initial count of zero. This sets the semaphore state 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. The CreateSemaphoreAPI is always used for this, because Windows CE does not implement the OpenSemaphoreAPI.

Use the CloseHandlefunction to close the handle. The system closes the handle automatically when the process terminates. When you close the last handle for a semaphore object, the semaphore object is destroyed.

 Last updated on Tuesday, May 18, 2004

© 2004 Microsoft Corporation. All rights reserved.