NaviServer - programmable web server
4.99  5.0

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

ns_thread(n) 5.0.0a naviserver "NaviServer Built-in Commands"

Name

ns_thread - Operate on threads

Table Of Contents

Synopsis

Description

The ns_thread command provides mechanisms to create and manipulate threads, facilitating concurrent programming within NaviServer.

COMMANDS

ns_thread create ?-detached? ?-name threadName? ?--? script

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.

Joinable threads (default):

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.

Detached threads:

Threads created with -detached run independently and do not need to be joined. This command returns an empty result for detached threads.

ns_thread handle

Returns the handle for the current thread.

ns_thread id

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.

ns_thread name ?name?

Returns the name of the current thread. If the optional name argument is provided, sets the current thread's name to the specified value.

ns_thread stackinfo

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.

ns_thread wait handle

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.

ns_thread yield

Causes the current thread to yield its CPU time, allowing other threads to execute.

EXAMPLES

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]"

See Also

ns_cond, ns_critsec, ns_mutex, ns_rwlock, ns_sema, ns_thread

Keywords

concurrency, multithreading, server built-in, synchronization, thread management, threading