ns_mutex create initializes a mutual exclusion lock and returns an ID for it.
ns_mutex destroy frees the resources associated with the specified mutual exclusion lock. The mutexid argument is the mutex ID returned by ns_mutex create when the mutex was created.
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 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)