thread(n) | thread(n) |
thread - Extension for script access to Tcl threading
package require Tcl 8.4
package require Thread ?2.6?
thread::create ?-joinable? ?-preserved? ?script?
thread::preserve ?id?
thread::release ?-wait? ?id?
thread::id
thread::errorproc ?procname?
thread::unwind
thread::exit
thread::names
thread::exists id
thread::send ?-async? ?-head? id script ?varname?
thread::broadcast id script
thread::wait
thread::eval ?-lock mutex? arg ?arg ...?
thread::join id
thread::configure id ?option? ?value? ?...?
thread::transfer id channel
thread::detach channel
thread::attach channel
thread::mutex
thread::mutex create ?-recursive?
thread::mutex destroy mutex
thread::mutex lock mutex
thread::mutex unlock mutex
thread::rwmutex
thread::rwmutex create
thread::rwmutex destroy mutex
thread::rwmutex rlock mutex
thread::rwmutex wlock mutex
thread::rwmutex unlock mutex
thread::cond
thread::cond create
thread::cond destroy cond
thread::cond notify cond
thread::cond wait cond mutex ?ms?
The thread extension creates threads that contain Tcl interpreters, and it lets you send scripts to those threads for evaluation. Additionaly, it provides script-level access to basic thread synchronization primitives, like mutexes and condition variables.
This section describes commands for creating and destroying threads and sending scripts to threads for evaluation.
If the optional script argument contains the thread::wait command the thread will enter into the event loop. If such command is not found in the script the thread will run the script to the end and exit. In that case, the handle may be safely ignored since it refers to a thread which does not exists any more at the time when the command returns.
Using flag -joinable it is possible to create a joinable thread, i.e. one upon whose exit can be waited upon by using thread::join command. Note that failure to join a thread created with -joinable flag results in resource and memory leaks.
Threads created by the thread::create cannot be destroyed forcefully. Consequently, there is no corresponding thread destroy command. A thread may only be released using the thread::release and if its internal reference count drops to zero, the thread is marked for exit. This kicks the thread out of the event loop servicing and the thread continues to execute commands passed in the script argument, following the thread::wait command. If this was the last command in the script, as usualy the case, the thread will exit.
It is possible to create a situation in which it may be impossible to terminate the thread, for example by putting some endless loop after the thread::wait or entering the event loop again by doing an vwait-type of command. In such cases, the thread may never exit. This is considered to be a bad practice and should be avoided if possible. This is best illustrated by the example below:
# You should never do ... set tid [thread::create { package require Http thread::wait vwait forever ; # <-- this! }]The thread created in the above example will never be able to exit. After it has been released with the last matching thread::release call, the thread will jump out of the thread::wait and continue to execute commands following. It will enter vwait command and wait endlessly for events. There is no way one can terminate such thread, so you wouldn't want to do this!
Each newly created has its internal reference counter set to 0 (zero), i.e. it is unreserved. This counter gets incremented by a call to thread::preserve and decremented by a call to thread::release command. These two commands implement simple but effective thread reservation system and offer predictable and controllable thread termination capabilities. It is however possible to create initialy preserved threads by using flag -preserved of the thread::create command. Threads created with this flag have the initial value of the reference counter of 1 (one), and are thus initially marked reserved.
With reference counting, one can implement controlled access to a shared Tcl thread. By incrementing the reference counter, the caller signalizes that he/she wishes to use the thread for a longer period of time. By decrementing the counter, caller signalizes that he/she has finished using the thread.
Optional flag -wait instructs the caller thread to wait for the target thread to exit, if the effect of the command would result in termination of the target thread, i.e. if the return result would be zero (0). Without the flag, the caller thread does not wait for the target thread to exit. Care must be taken when using the -wait, since this may block the caller thread indefinitely. This option has been implemented for some special uses of the extension and is deprecated for regular use. Regular users should create joinable threads by using the -joinable option of the thread::create command and the thread::join to wait for thread to exit.
myerrorproc thread_id errorInfo
This command stops a prior thread::wait command. Execution of the script passed to newly created thread will continue from the thread::wait command. If thread::wait was the last command in the script, the thread will exit. The command returns empty result but may trigger Tcl error with the message "target thread died" in some situations.
This command forces a thread stuck in the thread::wait command to unconditionaly exit. The execution of thread::exit command is guaranteed to leave the program memory in the unconsistent state, produce memory leaks and otherwise affect other subsytem(s) of the Tcl application in an unpredictable manner. The command returns empty result but may trigger Tcl error with the message "target thread died" in some situations.
Optional varname specifies name of the variable to store the result of the script. Without the -async flag, the command returns the evaluation code, similarily to the standard Tcl catch command. If, however, the -async flag is specified, the command returns immediately and caller can later vwait on ?varname? to get the result of the passed script
set t1 [thread::create] set t2 [thread::create] thread::send -async $t1 "set a 1" result thread::send -async $t2 "set b 2" result for {set i 0} {$i < 2} {incr i} { vwait result }In the above example, two threads were fed work and both of them were instructed to signalize the same variable "result" in the calling thread. The caller entered the event loop twice to get both results. Note, however, that the order of the received results may vary, depending on the current system load, type of work done, etc, etc.
Many threads can simultaneously send scripts to the target thread for execution. All of them are entered into the event queue of the target thread and executed on the FIFO basis, intermingled with optional other events pending in the event queue of the target thread. Using the optional ?-head? switch, scripts posted to the thread's event queue can be placed on the head, instead on the tail of the queue, thus being executed in the LIFO fashion.
set t1 [thread::create { # # Do some initialization work here # thread::wait ; # Enter the event loop }]
The -eventmark option, when set, limits the number of asynchronously posted scripts to the thread event loop. The thread::send -async command will block until the number of pending scripts in the event loop does not drop below the value configured with -eventmark. Default value for the -eventmark is 0 (zero) which effectively disables the checking, i.e. allows for unlimited number of posted scripts.
The -unwindonerror option, when set, causes the target thread to unwind if the result of the script processing resulted in error. Default value for the -unwindonerror is 0 (false), i.e. thread continues to process scripts after one of the posted scripts fails.
Due to the internal Tcl core implementation and the restriction on transferring shared channels, one has to take extra measures when transferring socket channels created by accepting the connection out of the socket commands callback procedures:
socket -server _Accept 2200 proc _Accept {s ipaddr port} { after idle [list Accept $s $ipaddr $port] } proc Accept {s ipaddr port} { set tid [thread::create] thread::transfer $tid $s }
Care has to be taken when using mutexes in an multithreading program. Improper use of mutexes may lead to various deadlock situations, especially when using exclusive mutexes.
The thread::mutex command supports following subcommands and options:
For reading the resource, thread should obtain a read lock on the resource. Read lock is non-exclusive, meaning that more than one thread can obtain a read lock to the same resource, without waiting on other readers. For changing the resource, however, a thread must obtain a exclusive write lock. This lock effectively blocks all threads from gaining the read-lock while the resource is been modified by the writer thread. Only after the write lock has been released, the resource may be read-locked again.
The thread::rwmutex command supports following subcommands and options:
The command supports following subcommands and options:
The ms command option, if given, must be an integer specifying time interval in milliseconds the command waits to be signalled. Otherwise the command waits on condition notify forever.
In multithreading programs, there are many situations where a thread has to wait for some event to happen until it is allowed to proceed. This is usually accomplished by repeatedly testing a condition under the mutex protection and waiting on the condition variable until the condition evaluates to true:
set mutex [thread::mutex create] set cond [thread::cond create] thread::mutex lock $mutex while {<some_condition_is_true>} { thread::cond wait $cond $mutex } # Do some work under mutex protection thread::mutex unlock $mutexRepeated testing of the condition is needed since the condition variable may get signalled without the condition being actually changed (spurious thread wake-ups, for example).
The fundamental threading model in Tcl is that there can be one or more Tcl interpreters per thread, but each Tcl interpreter should only be used by a single thread which created it. A "shared memory" abstraction is awkward to provide in Tcl because Tcl makes assumptions about variable and data ownership. Therefore this extension supports a simple form of threading where the main thread can manage several background, or "worker" threads. For example, an event-driven server can pass requests to worker threads, and then await responses from worker threads or new client requests. Everything goes through the common Tcl event loop, so message passing between threads works naturally with event-driven I/O, vwait on variables, and so forth. For the transfer of bulk information it is possible to move channels between the threads.
For advanced multithreading scripts, script-level access to two basic synchronization primitives, mutex and condition variables, is also supported.
http://www.tcl.tk/doc/howto/thread_model.html, tpool, tsv, ttrace
events, message passing, mutex, synchronization, thread
2.6 | Tcl Threading |