<manpage cat="package" id="thread" title="Tcl Threading" version="2.5">
<!--  
     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.5?</cmd></p>
<cmd>thread::create</cmd> ?<m>-joinable</m>? ?<m>-preserved</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> <m>id</m>
<cmd>thread::send</cmd> ?<m>-async</m>? <m>id</m> <m>script</m> ?<m>varname</m>?
<cmd>thread::wait</cmd>
<cmd>thread::eval</cmd> ?<m>-lock mutex</m>? <m>arg</m> ?<m>arg ...</m>?
<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::detach</cmd> <m>channel</m>
<cmd>thread::attach</cmd> <m>channel</m>
<cmd>thread::cond</cmd> <m>options</m>
<cmd>thread::mutex</cmd> <m>options</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.
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>-preserved</m>? ?<m>script</m>?
</command>
<desc>This command creates a thread that contains a Tcl interpreter. 
The Tcl interpreter either evaluates the optional <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, if any, of the
optional <m>script</m> is never returned to the caller.
<p>
The result of <cmd>thread::create</cmd> is the ID of the thread. This is
the small integer handle which indentifies the newly created thread for
all other package commands. The handle of the thread goes out of scope
automatically when thread is marked for exit (see the <cmd>thread::release</cmd>
command below).
If the optional <m>script</m> argument contains the <cmd>thread::wait</cmd>
command the thread will enter into the event loop. If such command is not found 
in the <m>script</m> the thread will run the <m>script</m> 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.</p>
Using flag <m>-joinable</m> 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. Note that only Tcl8.4+ core supports joinable 
threads. Note also that failure to join a thread created with 
<option>-joinable</option> flag results in resource and memory leaks. 
<p>
Threads created by the <cmd>thread::create</cmd> cannot be destroyed forcefully.
Consequently, there is no corresponding destroy-type command. A thread may only
be "released" using the <cmd>thread::release</cmd> 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 <m>script</m> argument, following the <cmd>thread::wait</cmd> 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 
<cmd>thread::wait</cmd> 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.</p>
<example>
    # You should NEVER do ...
    set tid [thread::create {
        packkage require Http
        thread::wait
        vwait forever ; # -- this!
    }]
</example>
<p>
The thread created in the above example will never be able to exit.
After it has been released with the last matching <cmd>thread::release</cmd> call
the thread will jump out of the <cmd>thread::wait</cmd> and continue to execute 
commands following. It will enter <cmd>vwait</cmd> command and wait endlessly for 
events. There is no way one can terminate such thread, so you wouldn't want to do this!
</p>
<p>
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 <cmd>thread::preserve</cmd> 
and decremented by a call to <cmd>thread::release</cmd> 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 <m>-preserved</m>. Threads 
created with this flag have the initial value of the reference counter of 1 (one). 
</p>
</desc>
</commanddef>

<commanddef>
<command> <cmd>thread::preserve</cmd> ?<m>id</m>?
</command>
<desc>This command 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. 
If called with the optional thread <m>id</m>, the command preserves the given
thread. Otherwise the current thread is preserved.<b/>
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.
</desc>
</commanddef>

<commanddef>
<command> <cmd>thread::release</cmd> ?<m>-wait</m>? ?<m>id</m>?
</command>
<desc>This command decrements the thread reference counter. Each call to this
command decrements the reference counter by one (1). 
If called with the optional thread <m>id</m>, the command releases the given
thread. Otherwise, the current thread is released.
Command returns the value of the reference counter after the decrement. When the 
reference counter reaches zero (0), the target thread is marked for termination. 
You should not reference the thread after the <cmd>thread::release</cmd> command 
returns zero or negative integer. The handle of the thread goes out of scope and 
should not be used any more. Any following reference to the same thread handle 
will result in Tcl error.<b/>
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 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 <m>-wait</m>, since this may block the caller thread indefinitely.
</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> ?<m>procname</m>?</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>
Use of this command is deprecated in favour of more advanced thread reservation
system implemented with <cmd>thread::preserve</cmd> and <cmd>thread::release</cmd> 
commands. Support for <cmd>thread::wait</cmd> will dissapear in some future 
major release of the extension.
<b/>
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 the script passed to the thread at the time of its 
creation, 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>
Use of this command is deprecated in favour of the 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. Support for 
<cmd>thread::exit</cmd> will dissapear in  some future major release of the extension.
<b/>
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. 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::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> <m>id</m></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> ?<m>-async</m>? <m>id</m> <m>script</m> ?<m>varname</m>?</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 any other
relevant Tcl/Tk command, like <cmd>update</cmd>, <cmd>vwait</cmd>, etc. 
<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>
<example>
    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 &lt; 2} {incr i} {
        vwait result
    }
</example>
<p>
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.</p>
<p>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.</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 command should only be used within 
the script passed to the <cmd>thread::create</cmd>. It should be the very last 
command in the script. If this is not the case, the exiting thread will continue
executing the script lines pass the <cmd>thread::wait</cmd> which is not what 
you usualy want and/or expect.
<example>
    set t1 [thread::create {
        #
        # Do some initialization work
        #
        thread::wait ; # Enter the event loop
    }
</example>

</desc>
</commanddef>

<commanddef>
<command><cmd>thread::eval</cmd> ?<m>-lock mutex</m>? <m>arg</m> ?<m>arg ...</m>?</command>
<desc>This command concatenates passed arguments and evaluates the 
resulting script under the mutex protection. If no mutex is specified,
using the <m>-lock mutex</m> optional argument, an internal
static mutex is used.
</desc>
</commanddef>

<commanddef>
<command><cmd>thread::join</cmd> <m>id</m></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. Upon the join
the handle of the thread has gone out of scope and should not be used
any more.
<p>NOTE: This command is available only when loaded into the Tcl8.4+ shell.</p>
</desc>
</commanddef>

<commanddef>
<command><cmd>thread::configure</cmd> <m>id</m> ?<m>option</m>? ?<m>value</m><m>? ?</m><m>option value</m><m>?...</m></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> <m>id</m> <m>channel</m></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.
<p>
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 <cmd>socket</cmd> commands callback procedures:
<example>
    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
    }
</example>
</p>

<p>NOTE: this command is available only when loaded into the Tcl8.4+ shell.</p>
</desc>
</commanddef>

<commanddef>
<command><cmd>thread::detach</cmd> <m>channel</m></command>
<desc>This detaches the specified <m>channel</m> from the
current thread and interpreter. After that, the current interpreter 
has no access to the channel anymore. The channel is in the parked
state until some other (or the same) thread attaches the channel
again with <cmd>thread::attach</cmd>.
Restrictions: same as for transferring shared channels with the
<cmd>thread::transfer</cmd> command.
<p>NOTE: this command is available only when loaded into the Tcl8.4+ shell.</p>
</desc>
</commanddef>

<commanddef>
<command><cmd>thread::attach</cmd> <m>channel</m></command>
<desc>This attaches the previously detached <m>channel</m> in the
current thread/interpreter. For already existing channels, 
the command does nothing, i.e. it is not an error to attach the
same channel more than once. The first operation will actualy
perform the operation, while all subsequent operation will just
do nothing.
Command throws error if the <m>channel</m> cannot be found in the
list of detached channels and/or in the current interpreter.
<p>NOTE: this command is available only when loaded into the Tcl8.4+ shell.</p>
</desc>
</commanddef>

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

</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>For advanced multithreading scripts, script-level access to two basic 
synchronization primitives, mutex and condition variables, is also supported.
</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>mutex</keyword>
<keyword>condition variable</keyword>
</keywords>
</manpage>
