ns_sema - Operate on semaphore-like objects
This command provides a mechanism to manipulate semaphore-like objects but are not inter-process capable like true semaphores. They are actually implemented with a mutex and a counter. The allowed options (which may be abbreviated) are:
Initializes a new semaphore object. The count argument specifies the initial value of the semaphore's counter. If count is not provided, the counter is initialized to zero. The command returns a handle for the semaphore object to be use by the other commands.
Destroys the semaphore handle and frees any resources it was using. Note: In the current implementation, this command is effectively a no-op; the semaphore will continue to exist until the server shuts down.
Releases the semaphore handle by incrementing the counter by one by default or by count otherwise. The thread will wake any threads blocking on this semaphore when count is equal to one.
This is what is commonly referred to as "semaphore up".
Waits for a semaphore handle to be greater than zero. Will block the thread until this is true. Decrements the counter by one when the counter is greater than zero.
This is what is commonly referred to as "semaphore down".
Using a semaphore to synchronize threads
set sema [ns_sema create] # Start a thread that waits for the semaphore ns_thread create -detached [subst { ns_log notice "... thread waits for $sema" ns_sema wait $sema ns_log notice "... thread proceeds" }] # Release the semaphore in two seconds to allow the waiting thread to proceed ns_sleep 2s ns_sema release $sema