NaviServer - programmable web server


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

ns_mutex(n) 4.99.3 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 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.

ns_mutex destroy object

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 object

ns_mutex lock acquires the specified mutual exclusion lock. The mutexid argument is the mutex ID returned by ns_mutex create when the mutex was created.

ns_mutex trylock object

ns_mutex trylock tries to acquire the specified mutual exclusion lock. The mutexid argument is the mutex ID returned by ns_mutex create when the mutex was created. 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 object

ns_mutex unlock unlocks the specified mutual exclusion lock. The mutexid argument is the mutex ID returned by ns_mutex create when the mutex was created.

EXAMPLES

At startup (for example, in your init.tcl procedure), open a shared file and create a lock for it:

ns_share Shared
set Shared(file) [open myfile.data]
set Shared(lock) [ns_mutex create]
detach $Shared(file)

Later (for example, in a request procedure), access the data file:

ns_share Shared
ns_mutex lock $Shared(lock)
catch {
... access $Shared(file) ...
}
ns_mutex unlock $Shared(lock)

Note: The "catch" is important so the lock isn't held if Tcl unwinds due to an error accessing the file. At shutdown (for example, in your shutdown procedure registered with ns_atshutdown), close the file and destroy the lock:

ns_share Shared
close $Shared(file)
ns_mutex destroy $Shared(lock)