Semaphore

A semaphore object is a synchronization object that maintains a count between zero and a specified maximum value. The count decrements 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.

Code Sample

! demonstrates how to use semaphore

cs=CreateObject("ACriticalSection")

if cs=Nothing

TestStatus=FAIL

ExitTest

endif

sm=CreateObject("ASemaphore")

if sm=Nothing

cs=Nothing

TestStatus=FAIL

ExitTest

endif

sm.InitialCount=3

 

s=""

cs.Lock()

for i=0 to 100

!maximum number of thread created is controlled by the semaphore InitialCount which is 3

if (not sm.Lock(0)) then exitloop

hThread=CreateThread(StringConcatThread, 0)

if hThread=0 then

TestStatus=FAIL

ExitTest

endif

next

! test if thread was completed

cs.Unlock()

if WaitForSingleObject(hThread, 1000)<>awaitObject0

TestStatus=FAIL

endif

if s<>"aaa" then

TestStatus=FAIL

endif

cs=Nothing

sm=Nothing