ns_thread - Operate on threads
The ns_thread command provides mechanisms to create and manipulate threads, facilitating concurrent programming within NaviServer.
Creates a new thread and executes the provided script. The optional -detached flag specifies that the thread runs detached, meaning it cannot be joined or waited for. If -name threadName is specified, the thread is named in the format -tcl-$name:$nr-, where $nr is a unique counter.
Threads created without -detached are joinable, allowing the main program to wait for their completion using ns_thread wait. These threads must be joined to ensure resources are properly freed.
Threads created with -detached run independently and do not need to be joined. This command returns an empty result for detached threads.
Returns the handle for the current thread.
Returns the current thread's ID as a hex value. This ID matches the third element in the sub-list returned from ns_info threads.
Returns the name of the current thread. If the optional name argument is provided, sets the current thread's name to the specified value.
Returns the maximum available size of the C stack and the currently free size of the C stack for the current thread in form of a Tcl dict. Example result: max 2048000 free 2024408.
Waits for the thread identified by handle to complete. If the thread is still running, the caller blocks until the thread finishes. The command returns the result of the script executed by the joined thread.
Note: Waiting on an invalid handle or a handle that has already been joined will cause the server to abort with a fatal error.
Causes the current thread to yield its CPU time, allowing other threads to execute.
Example 1: Creating and Waiting for a Thread
set threadHandle [ns_thread create { ns_log notice "Thread is executing" return "Finished processing" }] set result [ns_thread wait $threadHandle] ns_log notice "Main thread received result: $result"
Example 2: Detached Thread
ns_thread create -detached { ns_log notice "Detached thread running independently" }
Example 3: Setting and Retrieving Thread Name
ns_thread name "myCustomThread" ns_log notice "Thread name: [ns_thread name]"