Threads

The capability thread adds the commands of the Tcl Thread package: thread::*, tsv::*, tpool::*, and the mutexes and conditions of thread::mutex, thread::rwmutex, and thread::cond. The embedder turns it on and sets its limits. This page has the model, the limits, and the differences from the Thread package. References lists the manual pages that the commands follow.

Example

set ids {}
for {set i 0} {$i < 4} {incr i} {
    lappend ids [thread::create -joinable [format {
        set sum 0
        for {set k 0} {$k < 1000000} {incr k} { incr sum %d }
        tsv::incr totals all $sum
    } $i]]
}
foreach id $ids { thread::join $id }
puts [tsv::get totals all]
$ ztcl --allow thread threads.tcl
6000000

Speed

Each benchmark of bench/ is as fast as tclsh 8.6.16 with Thread 2.8.11, or faster. Wall time in milliseconds, best of 5 runs, on a 4-core Intel Core i7-6700K. Performance has the method.

Benchmark ztcl tclsh 8.6.16
thread_map.tcl: 1,000,000 integers in 8 parts 99 305
thread_pipe.tcl: 4 stages, 100,000 messages 605 706
thread_tsv.tcl: 8 threads, 100,000 tsv::incr each, 8 elements 1214 3276
thread_tpool.tcl: 8 workers, 100,000 jobs 466 639

The model

The capability and the limits

Interp.allow with Capability.thread turns on the commands. The runner flag is --allow thread. The embedder sets Interp.thread_limits before the call:

Field Default What it limits
max_threads 8 The threads that run at one time, the workers of the pools included. The main thread does not count.
compute_limit the compute limit of the host The compute units of one thread.
mem_limit 256 MiB The bytes of the heap of one thread.
total_compute no limit The compute units of all threads together.
total_mem 1 GiB The bytes of all threads together, with the shared variables, the queues, and the JIT data of the threads.
max_queue 10,000 The messages that wait in the queue of one thread.

With the capability on, a script is not deterministic: the order of the events of two threads depends on the system.

Messages

A message is a script, a result, or a job. The sender copies each value into a neutral form in the memory of the group. The form keeps the kind of a value: an integer, a double, a string, or a list of such values. So a list of numbers stays a list of numbers, and the receiver does no parse. The receiver copies the neutral form into its own heap on its own thread. Only the owner thread of a heap allocates from it.

A list deeper than 200 levels crosses as its string form. The copy then needs no deep recursion.

ztcl has no frozen, read-only form of a value that two threads share, so a large message costs one copy at each end.

The thread commands

Command ztcl behavior
thread::create ?-joinable? ?-preserved? ?-isolation LEVEL? ?-caps LIST? ?-compute UNITS? ?-meter NAME? ?script? Starts a thread and waits until its interpreter exists. With no script, the thread runs thread::wait. Without thread::wait, the thread ends at the end of its script. -compute caps the compute units of the thread below the limit of the group. -meter counts the thread in a meter of ztcl::meter, with the capability meter. -caps gives the thread only the listed capabilities, each one a capability of its creator. A thread with no thread in its list has no thread::* and tsv::* commands, also at the level process: it gets messages and answers them, and it cannot send a script to another thread.
thread::send ?-async? ?-head? id script ?varname? Queues the script at the target, or at the head with -head. Without -async, the sender waits for the result. While it waits, it runs the scripts that other threads send to it, so two threads that send to each other do not deadlock. With varname, the result goes to the variable, and the command gives the return code. With -async and varname, the variable gets the result later, in the event loop of the sender. A send to the own thread runs the script at once.
thread::broadcast script Sends the script with -async to each other thread.
thread::wait Runs the event loop of the thread until a release ends it.
thread::preserve ?id?, thread::release ?-wait? ?id? Change the reference count. At zero or below, thread::wait returns and the thread ends. -wait waits for the end.
thread::join id Waits for the end of a joinable thread and gives its exit status.
thread::id, thread::names, thread::exists id The own id, the ids of the running threads, and a test for one id.
thread::exit ?status? Ends the thread. catch cannot catch it. The main thread gives an error.
thread::cancel ?-unwind? id ?result? Stops the script of a thread at its next safe point. A cancel of a thread that runs no script has no effect, as in the Thread package. -unwind gives an error that catch cannot catch. The main thread cannot be the target.
thread::unwind The same as thread::release for the own thread.
thread::errorproc ?proc? Sets the procedure that gets the errors of all threads: proc id errorInfo. It runs in the thread that set it.
thread::configure id ?option? ?value? -eventmark N makes thread::send -async wait while the queue of the target has N messages. -unwindonerror bool ends the thread after a send with an error.
thread::eval ?-lock mutex? arg ?arg ...? Runs the script while it holds the mutex, or a mutex of the group.
thread::transfer id channel, thread::detach channel, thread::attach channel Move a file or socket channel between threads. A server socket and a command pipeline stay with their thread. The move removes the fileevent handlers of the channel. The channel commands exist on Linux, macOS, and Windows.

The shared variables

tsv keeps arrays of the group. Each array has its own lock, so two threads that use two arrays do not wait for each other. The table of the arrays has a lock of its own, which a command holds only to find or make an array.

The thread pools

tpool::create makes a pool of worker threads. A worker is a thread of the group with its own interpreter. It runs -initcmd one time and then keeps its interpreter between jobs, so a proc of -initcmd compiles one time for each worker.

The mutexes and the conditions

thread::mutex, thread::rwmutex, and thread::cond give handles of the group (mid0, rwmid0, cid0). A handle is a name in a table of the group, so a bad name is an error and never a bad pointer.

The event loop

The queue of a thread is a source of the event loop. vwait, update, and thread::wait run the scripts of the queue. A thread without the event capability has thread::wait and runs only its queue.

Stops, cancels, and teardown

A thread checks a stop flag at its safe points. Another thread sets the flag and then writes zero to mem_limit of the target interpreter. Each safe point of the interpreter and of the JIT code already compares the memory count with mem_limit, so the next safe point calls Interp.memPoint. There the target restores its limit and reads the flag. The fast path of the interpreter and of the JIT has no new check.

Isolated threads

Isolated threads compares the levels and the sandbox of each system, with a review list for the code of a parent. thread::create -isolation process runs the thread in a child process (ztcl#209). The child is the ztcl runner with one interpreter, and it talks to the parent over the protocol of docs/dev/isolation.md: sealed frames on a socket pair. A crash, a memory error, or a bad C package in the child ends only the child.

set t [thread::create -isolation process {proc sq x {expr {$x * $x}}; thread::wait}]
puts [thread::send $t {sq 12}]   ;# 144, from another process

A send from the child to the parent runs in the parent with the power of the parent, as with any thread. The sandbox limits the child, and a script the child sends to the parent goes past it.

Compiled code

A proc goes to a thread as its text in a script. Each thread compiles its own bytecode and its own JIT code.

The bytecode compiler inlines core commands such as set and incr. A command of the same name in another namespace stops the inline forms in the whole interpreter, because a call in that namespace finds that command first. The commands of tsv (tsv::set, tsv::incr, and the others) do not stop them. The cost of that rule: compiled code in the namespace tsv, for example a proc tsv::helper that calls set, runs the core set and not tsv::set. Tcl runs tsv::set there. Code outside the namespace tsv gets the same command as in Tcl. Without this rule, the commands of tsv stop the inline forms in each interpreter with the capability.

Platforms

The commands use std.Thread, so they build for Linux, macOS, and Windows. The channel commands of thread::transfer, thread::detach, and thread::attach need the channel capability, which exists on Linux, macOS, and Windows. The default WebAssembly build (ztcl.wasm) has no threads. zig build wasm-threads makes two WebAssembly builds with threads. See "WebAssembly" below. ThreadSanitizer runs on Linux: tools/tsan.sh.

WebAssembly

Each thread is a Web Worker, or a worker_threads worker in Node.js, with its own instance of the module. web/ztcl-threads.mjs is the host. WebAssembly has the API.

Differences from the Thread package