NaviServer - programmable web server

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

# ns_mutex(n) 4.99.8 naviserver "NaviServer Built-in Commands"

## Name

ns_mutex - Operate on mutexes

## Table Of Contents

## Synopsis

- ns_mutex option ?arg arg ...?
- ns_mutex create ?name?
- ns_mutex destroy mutexid
- ns_mutex lock mutexid
- ns_mutex eval mutexid script
- ns_mutex trylock mutexid
- ns_mutex unlock mutexid

## Description

This command provides a mechanism to manipulate mutexes.

## COMMANDS

ns_mutex option ?arg arg ...?

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 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. Before using this, you should probably look at

ns_mutex lock mutexid

  ns_mutex lock acquires the specified mutual exclusion lock.

ns_mutex eval mutexid script

  A conveniance 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.

ns_mutex trylock mutexid

  ns_mutex trylock 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.

ns_mutex unlock mutexid

  ns_mutex unlock unlocks the specified mutual exclusion lock.

## 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]
       ...
       ns_mutex lock $mutex
       catch {
       ... access file foo ...
       }
       ns_mutex unlock $mutex

Note: The catch 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 catch operation.

       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