ns_cond - Operate on condition variables
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.
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.
Initializes a new condition variable and returns a handle (condId) that can be used in subsequent ns_cond commands.
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.
Synonym for ns_cond signal.
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.
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.
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.
# 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