Chapter 14. Thread System

This chapter describes the Chez Scheme thread-system procedures
and syntactic forms.
The thread system is implemented on top of the Posix thread system
(pthreads).
Consult pthreads documentation on your system for basic details
of thread creation and interaction.

Most primitive Scheme procedures are thread-safe, meaning
that they can be called concurrently from multiple threads.
This includes allocation operations like cons and make-string,
accessors like car and vector-ref,
numeric operators like + and sqrt, and nondestructive
higher-level primitive operators like append and map.
Destructive operators are also thread safe if they are used to operate
on different objects; e.g., putprop can be called concurrently
in two threads if the symbols whose property lists are being modified
are different.
The last comment applies as well to I/O operations; see also
Section 14.6 for information on buffered ports.
Any hashtable procedure passed an eq or eqv
hashtable may need to rehash the table after a garbage collection
occurs and so must be considered destructive operations in this context
(Section 7.11).

The compiler and interpreter are also thread-safe, so two or more threads
can call any of the compiler or interpreter entry points, i.e.,
compile, compile-file, compile-script,
compile-port, or interpret at the same time.
The same is true for eval and load as long as
the default evaluator is used or is set explicitly to compile,
interpret, or some other thread-safe evaluator.

One restriction should be observed when one of multiple threads creates or
loads compiled code, however, which is that only that thread or
subsequently created children, or children of subsequently created
children, etc., should run the code.
This is because multiple-processor systems upon which threaded code may
run might not guarantee that the data and instruction caches are
synchronized across processors.

Section 14.1. Thread Creation

procedure: (fork-thread thunk)returns: a thread object

thunk must be a procedure that accepts zero arguments.

fork-thread Invokes thunk in a new thread and returns
a thread object.

At present, nothing can be done with the thread object returned by
fork-thread, other than to print it.
In the future, it may be possible to signal or kill threads using
the thread object as a handle on the thread.

Threads created by foreign code using some means other than
fork-thread must call Sactivate_thread
(Section 4.6) before touching any Scheme data
or calling any Scheme procedures.

mutex-acquire acquires the mutex identified by mutex.
The optional boolean argument block? defaults to
#t and specifies whether the thread should block
waiting for the mutex.
If block? is omitted or is true, the thread
blocks until the mutex has been acquired, and an unspecified
value is returned.

If block? is false and the mutex currently belongs
to a different thread, the current thread does not block.
Instead, mutex-acquire returns
immediately with the value #f to
indicate that the mutex is not available.
If block? is false and the mutex is successfully
acquired, mutex-acquire returns #t.

Mutexes are recursive in Posix threads terminology, which
means that the calling thread can use mutex-acquire to
(re)acquire a mutex it already has.
In this case, an equal number of mutex-release calls
is necessary to release the mutex.

procedure: (mutex-release mutex)returns: unspecified

mutex must be a mutex.

mutex-release releases the mutex identified by mutex.
Unpredictable behavior results if the mutex is not owned by the
calling thread.

syntax: (with-mutex mutexexp1exp2 ...)returns: the value of the final expression

with-mutex evaluates the expression mutex, which must
evaluate to a mutex, acquires the mutex, evaluates the body
exp1exp2 ..., and releases the mutex.
The mutex is released whether the body returns normally or
via a control operation (that is, throw to a continuation, perhaps because
of an error) that results in
a nonlocal exit from the with-mutex form.
If control subsequently returns to the body via a
continuation invocation, the mutex is reacquired.

Using with-mutex is generally more convenient and safer than using
mutex-acquire and mutex-release directly.

condition-wait waits for the condition
identified by the condition object cond.
The calling thread must have acquired the mutex identified by the mutex
mutex at the time condition-wait is
called.
mutex is released as a side effect of the call to
condition-wait.
When a thread is later released from the condition variable by one
of the procedures described below, mutex is reacquired
and condition-wait returns.

procedure: (condition-signal cond)returns: unspecified

cond must be a condition object.

condition-signal releases one of the threads waiting for the
condition identified by cond.

procedure: (condition-broadcast cond)returns: unspecified

cond must be a condition object.

condition-broadcast releases all of the threads waiting for the
condition identified by cond.

Section 14.4. Thread Parameters

See Section 11.10 for a general
discussion of parameters and the use of the optional second argument.

When a thread parameter is created, a separate location is set aside
in each current and future thread to hold the value of the parameter's
internal state variable.
(This location may be eliminated by the storage manager when the
parameter becomes inaccessible.)
Changes to the thread parameter in one thread are not seen by any
other thread.

When a new thread is created (see fork-thread),
the current value (not location) of each
thread parameter is inherited from the forking thread by the new thread.
Similarly, when a thread created by some other means is activated for the
first time (see Sactivate_thread in
Section 4.6), the current value (not location) of each
thread parameter is inherited from the main (original) thread by the new
thread.

Section 14.5. Built-in Parameters

Most built-in parameters are thread parameters, but some are global.
Here is a list of the built-in thread parameters.

The initial values of most of these are simply copied from the forking
thread.
Random seed is reset to its initial value when a thread is created.
Three other exceptions are reset-handler, exit-handler,
and abort-handler.
Each is bound to a procedure that exits immediately from the thread.
One effect of this is that errors in all but the main thread cause
the thread to exit after signaling an error.

Section 14.6. Buffered I/O

Chez Scheme buffers file I/O operations for efficiency, but buffered
I/O is not thread safe.
Two threads that write to or read from the same buffered port concurrently
can corrupt the port, resulting in buffer overruns and, ultimately,
invalid memory references.

Both input and output ports are normally buffered by default:
When running the threaded version of Chez Scheme, however,
the console output port is unbuffered by default.
This allows multiple threads to print error and/or debugging messages
to the console.
The output may be interleaved, even within the same line, but the
port will not become corrupted.

Threads that wish to allow multiple threads to write to a
file via a single port should use the unbuffered
flag when opening the file, e.g.:

(define p (open-output-file "prog.out" '(unbuffered)))

Although open-input-file also accepts the unbuffered
flag, "unbuffered" input ports are not entirely unbuffered because
at least one character of buffering is required to support peek-char
and unread-char.
Therefore, two threads should never read from the same input port
concurrently.

Section 14.7. Example

The following code implements a bounded queue using many of the
thread-system features.
A bounded queue has a fixed number of available slots.
Attempting to enqueue when the queue is full causes the calling thread
to block.
Attempting to dequeue from an empty queue causes the calling thread
to block.