<manpage cat="package" id="thread" title="Tcl Threading" version="2.4">
<!--  
     Copyright (c) 2000 Andreas Kupries
     Copyright (c) 2002 Zoran Vasiljevic 
     
     See the file "license.terms" for information on usage and redistribution
     of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 -->

<namesection>
<name>thread</name>
<desc>A Tcl extension implementing script level access to Tcl threading capabilities.</desc>
</namesection>

<synopsis>
<syntax>
<p>
<cmd>package require Thread ?2.4?</cmd></p>
<cmd>thread::create</cmd> ?<m>-joinable</m>? ?<m>script</m>?
<cmd>thread::preserve</cmd> <m>id</m>
<cmd>thread::release</cmd> ?<m>-wait</m>? <m>id</m>
<cmd>thread::id</cmd>
<cmd>thread::errorproc</cmd> ?<m>procname</m>?
<cmd>thread::unwind</cmd>
<cmd>thread::exit</cmd>
<cmd>thread::names</cmd>
<cmd>thread::exists</cmd>
<cmd>thread::send</cmd> <m>id</m> ?<m>-async</m>? <m>script</m> ?<m>varname</m>?
<cmd>thread::wait</cmd>
<cmd>thread::join</cmd> <m>id</m>
<cmd>thread::configure</cmd> <m>id</m> ?<m>option</m>? ?<m>value</m><m>? ?</m><m>option value</m><m>?...</m>
<cmd>thread::transfer</cmd> <m>id</m> <m>channel</m>

<cmd>thread::cond</cmd> <m>options</m>
<cmd>thread::mutex</cmd> <m>options</m>

<cmd>tsv::names</cmd> ?<m>pattern</m>?
<cmd>tsv::object</cmd> <m>array</m> <m>element</m>
<cmd>tsv::set</cmd> <m>array</m> <m>element</m> <m>value</m> 
<cmd>tsv::get</cmd> <m>array</m> <m>element</m> ?<m>varname</m>?
<cmd>tsv::unset</cmd> <m>array</m> ?<m>element</m>?
<cmd>tsv::exists</cmd> <m>array</m> ?<m>element</m>?
<cmd>tsv::pop</cmd> <m>array</m> <m>element</m>
<cmd>tsv::move</cmd> <m>array</m> <m>old</m> <m>new</m>
<cmd>tsv::incr</cmd> <m>array</m> <m>element</m> ?<m>increment</m>?
<cmd>tsv::append</cmd> <m>array</m> <m>element</m> <m>value</m> ?<m>value</m> ...?
<cmd>tsv::lappend</cmd> <m>array</m> <m>element</m> <m>value</m> ?<m>value</m> ...?
<cmd>tsv::linsert</cmd> <m>array</m> <m>element</m> <m>index</m> <m>value</m> ?<m>value</m> ...?
<cmd>tsv::lreplace</cmd> <m>array</m> <m>element</m> <m>first</m> <m>last</m> ?<m>value</m> ...?
<cmd>tsv::llength</cmd> <m>array</m> <m>element</m>
<cmd>tsv::lindex</cmd> <m>array</m> <m>element</m> <m>index</m>
<cmd>tsv::lrange</cmd> <m>array</m> <m>element</m> <m>first</m> <m>last</m>
<cmd>tsv::lsearch</cmd> <m>array</m> <m>element</m> ?<m>mode</m>? <m>pattern</m>
<cmd>tsv::lpop</cmd> <m>array</m> <m>element</m> ?<m>index</m>?
<cmd>tsv::lpush</cmd> <m>array</m> <m>element</m> <m>value</m> ?<m>index</m>?
</syntax>
</synopsis>

<section>
<title>DESCRIPTION</title>
<p>The <package>thread</package> extension creates threads that contain Tcl interpreters, 
and it lets you send scripts to those threads for evaluation. It also enables you to share data
between threads in a safe, protected fashion. Additionaly, it provides script-level access
to basic thread synchronization primitives, like mutexes and condition variables.
</p>
</section>

<section>
<title>COMMANDS</title>
<commandlist>

<p>
This section describes commands for creating and destroying threads
and sending scripts to threads for evaluation.</p>

<commanddef>
<command>
<cmd>thread::create</cmd> ?<m>-joinable</m>? ?<m>script</m>?
</command>
<desc>This command creates a thread that contains a Tcl interpreter. 
The Tcl interpreter either evaluates the <m>script</m>, if
specified, or it waits in the event loop for scripts that arrive via
the <cmd>thread::send</cmd> command. The result of <cmd>thread::create</cmd> is
the ID of the thread. The result, if any, of <m>script</m> is
ignored. Using flag <option>-joinable</option> it is possible to create a
joinable thread, i.e. one upon whose exit can be waited upon (by using
<cmd>thread::join</cmd> command).
</desc>
</commanddef>

<commanddef>
<command> <cmd>thread::preserve</cmd> <m>id</m>
</command>
<desc>This procedure increments the thread reference counter. Each call
to this command increments the reference counter by one (1). Command returns the value 
of the reference counter after the increment. 
<p>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, using the 
<cmd>thread::release</cmd> command, caller signalizes that he/she has finished using 
the thread.</p>
</desc>
</commanddef>

<commanddef>
<command> <cmd>thread::release</cmd> ?<m>-wait</m>? <m>id</m>
</command>
<desc>This procedure decrements the thread reference counter. Each call to this
command decrements the reference counter by one (1). Command returns
the value of the reference counter after the decrement. When the reference counter
reaches zero (0), the target thread is terminated.
<p>Optional flag <m>-wait</m> 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 is zero (0). Without the flag, the caller
thread does not wait for the target thread to exit. Care must be taken when using
the <m>-wait</m>, since this may block the caller thread indefinitely.</p>
</desc>
</commanddef>

<commanddef>
<command><cmd>thread::id</cmd> </command>
<desc>This command returns the ID of the current thread. 
</desc>
</commanddef>

<commanddef>
<command><cmd>thread::errorproc</cmd> </command>
<desc>This command sets a handler for errors that occur in scripts sent 
asynchronously, using the <option>-async</option> flag of the <cmd>thread::send</cmd>
command, to other threads. If no handler is specified, the current 
handler is returned. The empty string resets the handler to default 
(unspecified) value.
An uncaught error in a thread causes an error message to be sent
to the standard error channel. This default reporting scheme can be
changed by registering a procedure which is called to report the error.
The <m>proc</m> is called in the interpreter that invoked the 
<cmd>thread::errorproc</cmd> command. The <m>proc</m> is called like this:
<example>myerrorproc thread_id errorInfo</example>
</desc>
</commanddef>

<commanddef>
<command><cmd>thread::unwind</cmd></command>
<desc>This stops a prior <cmd>thread::wait</cmd>. Execution of the script will continue
from the <cmd>thread::wait</cmd> command. If <cmd>thread::wait</cmd> was the last command
in a thread, the thread will exit. The command usually returns empty result but
may trigger Tcl error with the message "target thread died" in some situations.
</desc>
</commanddef>

<commanddef>
<command><cmd>thread::exit</cmd></command>
<desc>This forces a thread stuck in the <cmd>thread::wait</cmd> to unconditionaly
exit. This 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.
<p>
Use of this command is deprecated in favour of the <cmd>thread::unwind</cmd> command
or more advanced thread reservation system implemented with <cmd>thread::preserve</cmd>
and <cmd>thread::release</cmd> commands. Use on your own risk and with extreme precaution.
The command usually  returns empty result but may trigger Tcl error with the message 
"target thread died" in some situations.</p>
</desc>
</commanddef>

<commanddef>
<command><cmd>thread::names</cmd></command>
<desc>This command returns a list of thread IDs. These are only for
threads that have been created via <cmd>thread::create</cmd>. If your
application creates other threads at the C level, they are not
reported by the <cmd>thread::names</cmd> command.
</desc>
</commanddef>

<commanddef>
<command><cmd>thread::exists</cmd> </command>
<desc>Returns true (1) if thread given by the ID parameter exists, false (0)
otherwise. This applies only for threads that have been created via 
<cmd>thread::create</cmd> command.
</desc>
</commanddef>

<commanddef>
<command><cmd>thread::send</cmd></command>
<desc>This command passes a <m>script</m> to another thread and, optionally, waits
for the result. If the <option>-async</option> flag is specified, the command does
not wait for the result and it returns empty string. The target thread must
enter it's event loop in order to receive scripts sent via this command.
This is done by default for threads created without a startup script. Threads
can enter the event loop explicitly by calling <cmd>thread::wait</cmd> or 
<cmd>vwait</cmd>. 
<p>Optional <m>varname</m> specifies name of the variable to store
the result of the <m>script</m>. Without the <option>-async</option> flag, the command
returns the evaluation code, similarily to the standard Tcl <cmd>catch</cmd> 
command.
If, however, the <option>-async</option> flag is specified, the command returns 
immediately and caller can later <cmd>vwait</cmd> on <m>varname</m> to get the
result of the passed <m>script</m>.
</p></desc>
</commanddef>

<commanddef>
<command><cmd>thread::wait</cmd></command>
<desc>This enters the event loop so a thread can receive messages from <cmd>thread::send</cmd>. 
This is equivalent to <samp>vwait <m>unusedvariable</m></samp> except that thread::unwind will
not unblock a <cmd>vwait</cmd>.
</desc>
</commanddef>

<commanddef>
<command><cmd>thread::join</cmd> </command>
<desc>This command waits for the thread with ID <m>id</m> to exit and
then returns it's exit code. Errors will be returned for threads which
are not joinable or already waited upon by another thread.
</desc>
</commanddef>

<commanddef>
<command><cmd>thread::configure</cmd> </command>
<desc>This command configures various low-level aspects of the thread with ID
<m>id</m> in the similar way as the standard Tcl command <cmd>fconfigure</cmd>
configures some Tcl channel options.
<p>Options currently supported are: <option>-eventmark</option> and <option>-unwindonerror</option>.
</p>
<p>The <option>-eventmark</option> option, when set, limits the number of asynchronously
posted scripts to the thread event loop. The <samp>thread::send -async</samp> 
command will block until the number of pending scripts in the event
loop does not drop below the value configured with <option>-eventmark</option>.
Default value for the <option>-eventmark</option> is 0 (zero) which effectively 
disables the checking, i.e. allows for unlimited number of posted scripts.
</p>
<p>The boolean <option>-unwindonerror</option> option, when set, causes the target thread
to unwind if the result of the script processing resulted in error.
Default value for the <option>-unwindonerror</option> is 0 (false), i.e. thread continues
to process scripts after one of the posted scripts fails.
</p></desc>
</commanddef>

<commanddef>
<command><cmd>thread::transfer</cmd> </command>
<desc>This moves the specified <m>channel</m> from the
current thread and interpreter to the main interpreter of the thread
with the given <m>id</m>. After the move the current interpreter has no
access to the channel anymore, but the main interpreter of the target
thread will be able to use it from now on.
The command waits until the other thread has incorporated the
channel. Because of this it is possible to deadlock the participating
threads by commanding the other through a synchronous
<cmd>thread::send</cmd> to transfer a channel to us. This easily extends
into longer loops of threads waiting for each other.
Other restrictions: The channel in question must not be shared among
multiple interpreters running in the sending thread. This
automatically excludes the special channels for standard input, output
and error.
</desc>
</commanddef>

<p>
This section describes commands used for script-level access to 
most common and basic thread synchronization primitives: mutexes and 
condition variables.</p>

<commanddef>
<command> <cmd>thread::mutex</cmd> <m>options</m></command>
<desc>This command provides script-level access to mutexes. Mutexes are most 
common thread synchronization primitives. They are used to synchronize
access from two or more threads to one or more shared resources. Care has to
be taken when using mutexes in an multithreading program. Improper use of 
mutexes may lead to various deadlock situations.

<p>The <cmd>thread::mutex</cmd> command supports following subcommands and options:</p>
<commandlist>
<commanddef>
<command><cmd>thread::mutex create</cmd></command>
<desc>Creates the mutex and returns it's opaque handle. This handle
should be used for any future reference to the newly created mutex.
</desc>
</commanddef>
<commanddef>
<command><cmd>thread::mutex destroy</cmd> <m>mutex</m></command>
<desc>Destroys the mutex <m>mutex</m>. Extreme care has to be taken that 
nobody is using the <m>mutex</m>, otherwise unexpected errors may happen.
</desc>
</commanddef>
<commanddef>
<command><cmd>thread::mutex lock</cmd> <m>mutex</m></command>
<desc>Locks the mutex <m>mutex</m>. Locking the mutex may deadlock the program
if same thread attempts to lock the same mutex twice without unlocking it
in between.
</desc>
</commanddef>
<commanddef>
<command><cmd>thread::mutex unlock</cmd> <m>mutex</m></command>
<desc>Unlocks the mutex <m>mutex</m> so some other thread may lock it again.
</desc>
</commanddef>
</commandlist></desc>
</commanddef>
<commanddef>
<command> <cmd>thread::cond</cmd> <m>options</m></command>
<desc>This command provides script-level access to condition variables. A condition
variable creates a safe environment for the program to test some condition, sleep
on it when false and be awakened when it might have become true. A condition variable
is always used in the conjuction with a mutex.

<p>The <cmd>thread::cond</cmd> supports following subcommands and options:</p>
<commandlist>
<commanddef>
<command><cmd>thread::cond create</cmd></command>
<desc>Creates the condition variable and returns it's opaque handle. This handle
should be used for any future reference to newly created condition variable.
</desc>
</commanddef>
<commanddef>
<command><cmd>thread::cond destroy</cmd> <m>cond</m></command>
<desc>Destroys condition variable <m>cond</m>. Extreme care has to be taken that nobody
is using (i.e. waiting on) the condition variable, otherwise unexpected 
errors may happen.
</desc>
</commanddef>
<commanddef>
<command><cmd>thread::cond notify</cmd> <m>cond</m></command>
<desc>Wakes up all threads waiting on the condition variable <m>cond</m>.
</desc>
</commanddef>
<commanddef>
<command><cmd>thread::cond wait</cmd> <m>cond</m> <m>mutex ?</m><m>ms?</m></command>
<desc>This command is used to suspend program execution until the condition
variable <m>cond</m> has been signalled (see <samp>thread::cond notify</samp>) or the
optional timer has expired. The <m>mutex</m> must be locked by the calling
thread on entrance to <samp>thread::cond wait</samp>. While waiting on the <m>cond</m>,
the command releases <m>mutex</m>. Before returning to the calling
thread, the command re-acquires <m>mutex</m> again. Unlocking the <m>mutex</m>
and waiting on the condition variable <m>cond</m> is done atomically.
<p>The <m>ms</m> command option, if given,  must be an integer specifying time 
interval in milliseconds the command waits to be signalled. Otherwise
the command waits forever.
</p>
<p>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:
</p>
<example>
set mutex [thread::mutex create]
set cond  [thread::cond  create]

thread::mutex lock
while {&lt;some_condition_is_true&gt;} {
   thread::cond wait $cond $mutex
}
thread::mutex unlock</example>
<p>Repeated 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).</p>
</desc>
</commanddef>
</commandlist>
</desc>
</commanddef>

<p>
This section describes commands implementing thread shared variables. A thread
shared variable is very similar to a Tcl array but in contrast to a Tcl array 
it is created in thread-shared memory and can be accessed from many threads at
the same time. Important feature of thread shared variable is that each access
to the variable is internaly protected by a mutex so script programmer does not have
to take care about locking the variable himself.</p>

<commanddef>
<command><cmd>tsv::names</cmd></command>
<desc>Returns names of shared variables matching optional <m>pattern</m> or all known
variables if pattern is ommited.
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::object</cmd></command>
<desc>Creates object accessor command for the <m>element</m> in the given shared 
<m>array</m>. Using this command, one can apply most of the other shared variable
commands as method functions of the element object command:
<example>
% tsv::set foo bar "A shared string"
% set string [tsv::object foo bar]
% $string append " appended"
=&gt; A shared string appended</example>
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::set</cmd></command>
<desc>Sets the value of the <m>element</m>  in the shared <m>array</m> to
<m>value</m> and returns the value. The <m>value</m> may be ommited, and
the command will return the current value of the <m>element</m>. If the 
element cannot be found, error is triggered.
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::get</cmd></command>
<desc>Retrieves a value of the <m>element</m> located in the shared <m>array</m>.
The command triggers error if the <m>element</m> is not found. If the optional 
<m>varname</m> is given, the value  is stored in the named variable. In this case, 
the command returns true (1) if <m>element</m> is found or false (0) if the 
<m>element</m> is not found.
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::unset</cmd></command>
<desc>Deletes the <m>element</m> in the shared <m>array</m>. If the <m>element</m>
is not given, it deletes the whole <m>array</m>.
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::exists</cmd></command>
<desc>Checks wether the <m>element</m> exists in the shared <m>array</m>.
If the <m>element</m> is not given it tests the existence of the 
<m>array</m> itself. Returns true (1) if the item exists, 
false (0) if not.
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::pop</cmd></command>
<desc>Returns value of the <m>element</m> in the shared <m>array</m> variable
and unsets the <m>element</m> in one atomic operation.
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::move</cmd></command>
<desc>Renames the element <m>old</m> to <m>new</m> in the shared <m>array</m>.
This effectively performs an get/unset/set sequence of operations
but in one atomic step.
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::incr</cmd></command>
<desc>Similar to standard Tcl <cmd>incr</cmd> but increments the value of the
<m>element</m> in shared <m>array</m> instead of the Tcl variable.
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::append</cmd></command>
<desc>Similar to standard Tcl <cmd>append</cmd> but appends one or more values
to the <m>element</m> in the shared <m>array</m> instead of the Tcl variable.
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::lappend</cmd></command>
<desc>Similar to standard Tcl <cmd>lappend</cmd> but appends one or more values
to the list <m>element</m> in the shared <m>array</m> instead of the Tcl variable.
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::linsert</cmd></command>
<desc>Similar to standard Tcl <cmd>linsert</cmd> but inserts one or more values at the 
<m>index</m> list position in the list <m>element</m> in the shared <m>array</m>
instead of the Tcl variable.
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::lreplace</cmd></command>
<desc>Similar to standard Tcl <cmd>lreplace</cmd> but replaces one or more values
from the list <m>element</m> in the shared <m>array</m> instead of the Tcl variable.
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::llength</cmd></command>
<desc>Similar to standard Tcl <cmd>llength</cmd> but returns length of the list
<m>element</m> in the shared <m>array</m> instead of the Tcl variable.
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::lindex</cmd></command>
<desc>Similar to standard Tcl <cmd>lindex</cmd> but returns value at the <m>index</m>
list position from the list <m>element</m> in the shared <m>array</m>
instead of the Tcl variable.
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::lrange</cmd></command>
<desc>Similar to standard Tcl <cmd>lrange</cmd> but returns values between <m>first</m>
and <m>last</m> list position from the list <m>element</m> in the shared <m>array</m>
instead of the Tcl variable.
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::lsearch</cmd></command>
<desc>Similar to standard Tcl <cmd>lsearch</cmd> but searches the list <m>element</m>
in the shared <m>array</m> instead of the Tcl variable.
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::lpop</cmd></command>
<desc>Splices out the value at the <m>index</m> list position from the list <m>element</m>
in the shared <m>array</m>. If <m>index</m> is not specified, it defaults to zero.
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::lpush</cmd></command>
<desc>Inserts the <m>value</m> at the <m>index</m> list position in the list <m>element</m>
in the shared <m>array</m>. If <m>index</m> is not specified, it defaults to zero.
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::array</cmd></command>
<desc>This command supports most of the options of the standard Tcl <cmd>array</cmd>
command like:
<commandlist>

<commanddef>
<command><cmd>tsv::array set</cmd></command>
<desc>Does the same as standard Tcl <samp>array set</samp>
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::array get</cmd></command>
<desc>Does the same as standard Tcl <samp>array get</samp>
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::array names</cmd></command>
<desc>Does the same as standard Tcl <samp>array names</samp>
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::array size</cmd></command>
<desc>Does the same as standard Tcl <samp>array size</samp>
</desc>
</commanddef>

<commanddef>
<command><cmd>tsv::array reset</cmd></command>
<desc>Does the same as standard Tcl <samp>array set</samp> but
it clears the array and sets new values atomically.
</desc>
</commanddef>

</commandlist>
</desc>
</commanddef>
</commandlist>
</section>

<section>
<title>DISCUSSION</title>
<p>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, 
<cmd>vwait</cmd> on variables, and so forth. For the transfer of bulk information
it is possible to move channels between the threads.
</p>
<p>In addition, this extension provides simple but effective way of
threads to access thread-shared data without the need of explicit locking.
This is implemented with shared variable arrays. Shared variable array
is a data structure similar to Tcl array but internaly protected with mutex. 
Several threads can access array elements without synchronizing themselves.
Script programmer can create any number of such arrays and access them
or their elements from any thread, without explicit locking.
</p>
<p>For advanced multithreading scripts, script-level access to two basic 
synchronization primitives, mutex and condition variables, is also supported.
</p>
</section>
<section>
<title>CREDITS</title>
<p>Shared variable arrays are inspired by the nsv interface found in 
AOLserver 3.+ highly scalable Web server from America Online.
</p>
</section>
<seealso>
<ref href="http://www.tcl.tk/doc/howto/thread_model.html">Guide to the Tcl threading model
</ref>
</seealso>
<keywords>
<keyword>threads</keyword>
<keyword>events</keyword>
<keyword>message passing</keyword>
<keyword>synchronization</keyword>
<keyword>shared variables</keyword>
<keyword>mutex</keyword>
<keyword>condition variable</keyword>
</keywords>
</manpage>
