NaviServer - programmable web server
4.99  5.0

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

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

Name

ns_cond - Operate on condition variables

Table Of Contents

Synopsis

Description

The ns_cond command provides mechanisms for manipulating condition variables, which are essential for thread synchronization. Condition variables allow threads to wait for specific conditions to be met while holding a mutex for coordination with other threads.

COMMANDS

ns_cond broadcast condId

Wakes up all threads currently waiting on the specified condition variable identified by condId. This is used when multiple threads need to be notified simultaneously that a condition has changed.

ns_cond create

Initializes a new condition variable and returns a handle (condId) that can be used in subsequent ns_cond commands.

ns_cond destroy condId

Destroys the condition variable identified by condId and releases any associated resources. Note: Ensure that no threads are waiting on the condition variable when calling this command, as undefined behavior (such as server crashes) can occur. Currently, this operation is a no-op, meaning the condition variable will persist until the server shuts down.

ns_cond set condId

Synonym for ns_cond signal.

ns_cond signal condId

Wakes up one thread waiting on the specified condId. If more than one thread is waiting, only one will be notified. If no threads are waiting, the operation has no effect.

ns_cond abswait condId mutexId ?timeout?

Waits on the condition variable condId while holding the mutex identified by mutexId. The timeout specifies an absolute time in Unix epoch seconds to wait until. Returns 1 on success (condition met) or 0 on timeout.

ns_cond wait condId mutexId ?timeout?

Waits on the condition variable condId while holding the mutex mutexId. If timeout is provided, the thread will wait for up to timeout seconds; otherwise, it waits indefinitely until the condition is signaled. Returns 1 on success (condition met) or 0 on timeout.

EXAMPLES

 # Create a condition variable and a mutex
 set condId [ns_cond create]
 set mutexId [ns_mutex create condition-example]
 
 #
 # Thread 1: Wait for the condition
 #
 ns_thread create -detached [subst {
    ns_mutex lock $mutexId
    if {[ns_cond wait $condId $mutexId 10] == 1} {
        ns_log notice "==============  thread 1: Condition met, resuming work"
    } else {
        ns_log notice "==============  thread 1: Timed out waiting for condition"
    }
    ns_mutex unlock $mutexId
 }]
 
 #
 # Thread 2: Signal the condition, after a little sleep
 #
 ns_sleep 2s
 ns_cond signal $condId

See Also

ns_critsec, ns_mutex, ns_rwlock, ns_sema, ns_thread

Keywords

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