[ Team LiB ] Previous Section Next Section

Thread Safety

The Tcl C library is thread-safe. This means that you can use Tcl in an application that uses threads. The threading model for Tcl is a thread can have one or more Tcl interpreters, but a Tcl interpreter cannot be used by different threads. For communication between threads, Tcl provides the ability to send Tcl scripts to an interpreter in another thread.

The Tcl C library provides mutex variables, condition variables, and thread local storage. These primitives are used by Tcl internally, and they are meant to be used by Tcl extensions to serialize access to their own data structures. The Tcl library allows different implementations of the threading primitives. This is done to support Unix, Windows, and Macintosh. Tcl uses native threads on Windows, and Posix pthreads on Unix. MacOS does not have true threads, so it is easy to provide the required thread API.

The testthread Command

Tcl 8.1 does not export threads to the script level, except through the testthread testing command. (Chapter 21 describes the Thread extension built for Tcl 8.3 and Tcl 8.4 that extends the testthread package described here.) You can try out testthread by compiling the tcltest program instead of the regular tclsh shell. Table 55-1 describes the testthread operations, which are implemented in the generic/tclThreadTest.c file. These operations are likely to be similar to those of the API provided by the more general threading extension, but you should check the documentation associated with that extension for more details.

Table 55-1. The testthread command

testthread create ?script?

Creates a new thread and a Tcl interpreter. Runs script after creating the Tcl interpreter. If no script is specified, the new thread waits with testthread wait.

testthread id

Returns the thread ID of the current thread.

testthread errorproc proc

Registers proc as a handler for errors from other threads. If they terminate with a Tcl error, this procedure is called with the error message and errorInfo values as arguments. Otherwise, a message is printed to stderr.

testthread exit

Terminates the current thread.

testthread names

Returns a list of thread IDs.

testthread send id ?-async? script

Sends a script to another thread for evaluation. If -async is specified, the command does not wait for the result.

testthread wait

Enters the event loop. This is used by worker threads to wait for scripts to arrive for evaluation. Threads can also use vwait for this purpose.

    [ Team LiB ] Previous Section Next Section