NaviServer - programmable web server
4.99  5.0

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

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

Name

ns_mutex - Operate on mutexes

Table Of Contents

Synopsis

Description

This command provides a mechanism to manipulate mutexes.

COMMANDS

ns_mutex create ?name?

Initializes a new mutual exclusion (mutex) lock and returns a handle to it. If name is provided the mutex name will be set to this value. The command returns a mutex ID which used as argument for the commands operating on this mutex.

ns_mutex destroy mutexid

Destroys the mutex mutexid and frees any resources it was using. NOTE: The mutex must be unlocked, or else the behavior is undefined and will likely crash the server. Actually, in the current implementation, this operation is a no-op, the mutex object will live until the server shuts down.

ns_mutex lock mutexid

Acquires the specified mutual exclusion lock. If mutexid does not exist, it is auto-created (not recommended).

ns_mutex eval mutexid script

A convenience function to lock the specified mutex, run the script and unlock the mutex finally. The result and error condition of the script are returned by the command. If mutexid does not exist, it is auto-created (not recommended).

ns_mutex trylock mutexid

Tries to acquire the specified mutual exclusion lock. If the mutex is locked successfully, return value of 0 is returned. Non-zero return value indicates that the mutex is already locked by someone else. If mutexid does not exist, it is auto-created (not recommended).

ns_mutex unlock mutexid

Unlocks the specified mutual exclusion lock. The lock object mutexid must pre-exist.

EXAMPLES

At startup (for example, in your init.tcl procedure), create a mutex named "foo" and remember it in a shared variable.

 nsv_set mutex foo [ns_mutex create]

Later (for example, in a request procedure), you might use this mutex to lock the access to the file:

 set mutex [nsv_get mutex foo]
 try {
    ns_mutex lock $mutex
     ... access file foo ...
 } finally {
    ns_mutex unlock $mutex
 }

Note: The try ... finally in the snipped above is important so the lock isn't held if Tcl unwinds due to an error accessing the file.

Alternatively, one can use the following shorter version, where the eval subcommand takes care of locking/unlocking of the mutex without the need for the try command.

 ns_mutex eval $mutex {
    ... access file foo ...
 }

At shutdown (for example, in your shutdown procedure registered with ns_atshutdown), one can destroy the mutex (not strictly necessary).

 ns_mutex destroy [nsv_get mutex foo]
 nsv_unset mutex foo

See Also

ns_atsignal, ns_cond, ns_critsec, ns_rwlock, ns_sema, ns_thread

Keywords

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