11.1 Threads (original) (raw)

11.1 Threads🔗

+Concurrency and Synchronization in The Racket Guide introduces threads.

See Threads for basic information on the Racket thread model. See also Futures and Places.

When a thread is created, it is placed into the management of thecurrent custodian and added to the current thread group. A thread can have any number of custodian managers added through thread-resume. The allocation made by a thread is accounted to the thread’s custodian managers. See custodian-limit-memory for examples.

A thread that has not terminated can be garbage collected (seeGarbage Collection) if it is unreachable and suspended or if it is unreachable and blocked on only unreachable events through functions such as semaphore-wait, semaphore-wait/enable-break,channel-put, channel-get, sync,sync/enable-break, or thread-wait. Beware, however, of a limitation on place-channel blocking; see thecaveat in Places.

In GRacket, a handler thread for an eventspace is blocked on an internal semaphore when its event queue is empty. Thus, the handler thread is collectible when the eventspace is unreachable and contains no visible windows or running timers.

A thread can be used as a synchronizable event (seeEvents). A thread is ready for synchronization whenthread-wait would not block; the synchronization result of a thread is the thread itself.

11.1.1 Creating Threads🔗

Calls thunk with no arguments in a new thread of control. Thethread procedure returns immediately with a thread descriptor value. When the invocation of thunk returns, the thread created to invoke thunk terminates.

Returns #t ifv is a thread descriptor, #f otherwise.

Returns the thread descriptor for the currently executing thread.

Like thread, except that “killing” the thread throughkill-thread or custodian-shutdown-all merely suspends the thread instead of terminating it.

Creates a nested thread managed by cust to executethunk. (The nested thread’s current custodian is inherited from the creating thread, independent of the cust argument.) The current thread blocks until thunk returns, and the result of the call-in-nested-thread call is the result returned bythunk.

The nested thread’s exception handler is initialized to a procedure that jumps to the beginning of the thread and transfers the exception to the original thread. The handler thus terminates the nested thread and re-raises the exception in the original thread.

If the thread created by call-in-nested-thread dies beforethunk returns, the exn:fail exception is raised in the original thread. If the original thread is killed before thunkreturns, a break is queued for the nested thread.

If a break is queued for the original thread (withbreak-thread) while the nested thread is running, the break is redirected to the nested thread. If a break is already queued on the original thread when the nested thread is created, the break is moved to the nested thread. If a break remains queued on the nested thread when it completes, the break is moved to the original thread.

If the thread created by call-in-nested-thread dies while itself in a call to call-in-nested-thread, the outer call tocall-in-nested-thread waits for the innermost nested thread to complete, and any breaks pending on the inner threads are moved to the original thread.

11.1.2 Suspending, Resuming, and Killing Threads🔗

Immediately suspends the execution of thd if it is running. If the thread has terminated or is already suspended,thread-suspend has no effect. The thread remains suspended (i.e., it does not execute) until it is resumed withthread-resume. If the current custodian does not solely manage thd (i.e., some custodian of thdis not the current custodian or a subordinate), theexn:fail:contract exception is raised, and the thread is not suspended.

Resumes the execution of thd if it is suspended and has at least one custodian (possibly added through benefactor, as described below). If the thread has terminated, or if the thread is already running and benefactor is not supplied, or if the thread has no custodian and benefactor is not supplied, thenthread-resume has no effect. Otherwise, ifbenefactor is supplied, it triggers up to three additional actions:

Terminates the specified thread immediately, or suspends the thread ifthd was created withthread/suspend-to-kill. Terminating the main thread exits the application. If thd has already terminated,kill-thread does nothing. If the current custodiandoes not solely manage thd (i.e., some custodian of thdis not the current custodian or a subordinate), theexn:fail:contract exception is raised, and the thread is not killed or suspended.

Unless otherwise noted, procedures provided by Racket (and GRacket) are kill-safe and suspend-safe; that is, killing or suspending a thread never interferes with the application of procedures in other threads. For example, if a thread is killed while extracting a character from an input port, the character is either completely consumed or not consumed, and other threads can safely use the port.

(break-thread thd [kind]) → void?
thd : thread?
kind : (or/c #f 'hang-up 'terminate) = #f

Registers a break with the specified thread. The optional kind value indicates the kind of break to register, where #f, 'hang-up, and 'terminatecorrespond to interrupt, hang-up, and terminate breaks respectively. If breaking is disabled in thd, the break will be ignored until breaks are re-enabled. See Breaks for details.

Causes the current thread to sleep until at least secsseconds have passed after it starts sleeping. A zero value forsecs simply acts as a hint to allow other threads to execute. The value of secs can be a non-integer to request a sleep duration to any precision; the precision of the actual sleep time is unspecified.

Returns #t if thdhas not terminated and is not suspended, #f otherwise.

Returns #t if thd has terminated, #fotherwise.

11.1.3 Synchronizing Thread State🔗

Blocks execution of the current thread until thd has terminated. Note that (thread-wait (current-thread))deadlocks the current thread, but a break can end the deadlock if breaking is enabled and if the thread is the main thread or otherwise accessible; see Breaks.

Unless thd was created with thread/suspend-to-kill, a (thread-wait thd) may potentially continue even ifthd is otherwise inaccessible, because a custodianshut down could terminate the thread. As a result, a thread blocking with thread-wait normally cannot be garbage collected (seeGarbage Collection). As a special case, however, (thread-wait thd) blocks without preventing garbage collection of the thread ifthd is the current thread, since the thread could only continue if a break escapes from the wait.

A thread waiting on the result of (thread-dead-evt thd)normally cannot itself be garbage collected, unless thd was created with thread/suspend-to-kill, along the same lines as waiting via thread-wait. However, there is no special case for waiting on the result of (thread-dead-evt thd) wherethd is the current thread.

For a given thd, thread-dead-evt always returns the same (i.e., eq?) result.

Returns a synchronizable event (see Events) that becomes ready for synchronization when thd is running. (If thd has terminated, the event never becomes ready.) If thd runs and is then suspended after a call to thread-resume-evt, the result event remains ready; after each suspend of thd a fresh event is generated to be returned by thread-resume-evt. The result of the event is thd, but if thd is never resumed, then reference to the event does not prevent thdfrom being garbage collected (see Garbage Collection).

Returns a synchronizable event (see Events) that becomes ready for synchronization when thd is suspended. (If thd has terminated, the event will never unblock.) If thd is suspended and then resumes after a call tothread-suspend-evt, the result event remains ready; each resume of thd creates a fresh event to be returned bythread-suspend-evt. The result of the event is thd, but if thd was created with thread (as opposed to thread/suspend-to-kill) and is never resumed, then reference to the event does not prevent thdfrom being garbage collected (see Garbage Collection).

If thd was created with thread/suspend-to-kill, then waiting on (thread-suspend-evt thd) prevents garbage collection of the waiting thread in the same way as(thread-dead-evt another-thd) for a another-thdcreated via thread. Furthermore, since the event result isthd, waiting on (thread-suspend-evt thd) prevents garbage collection of thd.

11.1.4 Thread Mailboxes🔗

Each thread has a mailbox through which it can receive arbitrary messages. In other words, each thread has a built-in asynchronous channel.

+See also Buffered Asynchronous Channels.

Queues v as a message to thd without blocking. If the message is queued, the result is #. If thdstops running—as in thread-running?—before the message is queued, then fail-thunk is called (through a tail call) if it is a procedure to produce the result, or #f is returned iffail-thunk is #f.

Receives and dequeues a message queued for the current thread, if any. If no message is available, thread-receive blocks until one is available.

Receives and dequeues a message queued for the current thread, if any, or returns #f immediately if no message is available.

Pushes the elements of lst back onto the front of the current thread’s queue. The elements are pushed one by one, so that the first available message is the last element of lst.