Title: Semaphore Object synchronization counter
1Semaphore Object synchronization counter
An application uses a semaphore to limit the
number of threads using a resource. Semaphore can
be used across processes or within a single
process. A semaphore is a synchronization
object that maintains a count between zero and a
maximum value. It is used as a counting resource
gate, limiting the use of the resource by
counting threads as they pass in and out the
gate. The semaphore-objects state is set to
signaled (gate is open) when its count is greater
than zero and nonsignaled (gate is closed) when
its count is zero. A thread can call a
CreateSemaphore function to create named or
unnamed semaphore object Named Object.
2Semaphore Object Ownership
Before a thread uses the resource, it specifies
the semaphore-object handle in a call to a wait
function. 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, the thread calls ReleaseSemaphore to
increase the semaphore count by one.
ReleaseSemaphore can be also used during the
initialization of an application The application
can create a semaphore with initial count of
zero. This sets the semaphore states 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
permits normal access to the protected resource.
3CreateSemaphore Function
HANDLE CreateSemaphore( LPSECURITY_ATTRIBUTES
lpSemaphoreAttributes, LONG
lInitialCount,// Initial Count LONG
lMaximumCount,//
Maximum Count LPCSTR
lpname ) // Specify the object name
ReleaseSemaphore Function
BOOL ReleaseSemaphore( HANDLE
hSemaphore, // Specify the semaphore object
handle LONG lReleaseCount, //
Increment counter by LPONG
lpPreviousCount) // Pointer to Long to receive
previous state
Return values nonzero indicates success, zero
indicates failure.