NaviServer - programmable web server
4.99  5.0

[ Main Table Of Contents | Table Of Contents | Keyword Index ]

ns_sema(n) 5.0.0a naviserver "NaviServer Built-in Commands"

Name

ns_sema - Operate on semaphore-like objects

Table Of Contents

Synopsis

Description

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:

COMMANDS

ns_sema create ?count?

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.

ns_sema destroy handle

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.

ns_sema release handle ?count?

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".

ns_sema wait handle

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".

EXAMPLES

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

See Also

ns_cond, ns_critsec, ns_mutex, ns_rwlock, ns_thread

Keywords

concurrency, mutex, semaphore, server built-in, synchronization, threading