ns_mutex - Operate on mutexes
This command provides a mechanism to manipulate mutexes.
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.
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 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 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 unlocks the specified mutual exclusion lock. The mutexid argument is the mutex ID returned by ns_mutex create when the mutex was created.
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)