Scheme threads
last modified November 25, 2026 Guile 3.0
A thread is an independent flow of execution inside a program.
Threads share the memory of the program, so they can work on the same data
at the same time; on a machine with several processor cores they also run
in parallel. Guile has real operating system threads and provides them
in the (ice-9 threads) module. Threads run in an order that
the program does not control, so the outputs and timings in this article
may differ from run to run. The examples are run with GNU Guile 3.0.7 on a
machine with eight cores.
A first thread
call-with-new-thread starts a thread that calls a procedure
without arguments. join-thread waits for the thread to finish
and returns the value of the procedure.
(use-modules (ice-9 threads))
(define (sum-range from to)
(let loop ((i from) (acc 0))
(if (> i to)
acc
(loop (+ i 1) (+ acc i)))))
(define worker
(call-with-new-thread
(lambda ()
(sum-range 1 1000000))))
(display "the main thread goes on")
(newline)
(display (join-thread worker))
(newline)
(display (thread-exited? worker))
(newline)
The worker sums the numbers up to a million while the main thread prints
its message. join-thread blocks until the worker is done, so
the sum is printed after the message. thread-exited? tells
whether a thread has finished. Running one computation in a thread does
not make it faster; the benefit comes from running several at once.
$ guile worker.scm the main thread goes on 500000500000 #t
Several threads
Threads started one after another run at the same time. Their output interleaves in an order that depends on how long each step takes and on the scheduler of the operating system.
(use-modules (ice-9 threads))
(define (worker name steps pause)
(lambda ()
(do ((i 1 (+ i 1)))
((> i steps) name)
(format #t "~a step ~a~%" name i)
(usleep pause))))
(define threads
(list (call-with-new-thread (worker "fast" 4 30000))
(call-with-new-thread (worker "slow" 2 70000))))
(display (map join-thread threads))
(newline)
worker returns a procedure that prints a number of steps and
sleeps between them with usleep, which takes microseconds.
The fast worker pauses for 30 ms and the slow one for 70 ms, so the fast
one prints more often. Mapping join-thread over the threads
waits for both and collects their results. The workers write to the same
output port; the mutex section shows how to keep shared resources in
order.
$ guile several.scm fast step 1 slow step 1 fast step 2 fast step 3 slow step 2 fast step 4 (fast slow)
A race condition
When several threads change the same variable, their updates can get in each other's way. Incrementing a counter reads the old value, adds one, and writes the result back; another thread may write in between.
(use-modules (ice-9 threads))
(define counter 0)
(define (increment-many n)
(do ((i 0 (+ i 1)))
((= i n))
(set! counter (+ counter 1))))
(define (run-threads count thunk)
(let ((threads (map (lambda (i) (call-with-new-thread thunk))
(iota count))))
(for-each join-thread threads)))
(run-threads 4 (lambda () (increment-many 100000)))
(format #t "expected 400000, got ~a~%" counter)
(set! counter 0)
(run-threads 4 (lambda () (increment-many 100000)))
(format #t "expected 400000, got ~a~%" counter)
Four threads each increment the shared counter 100,000 times.
run-threads starts them and waits for all of them. The final
count falls far short of 400,000: when two threads read the same old value,
one of the increments is lost. The result is different in every run. This
kind of bug, which depends on timing, is called a race
condition.
$ guile race.scm expected 400000, got 138072 expected 400000, got 160186
Mutexes
A mutex (mutual exclusion lock) lets only one thread at a time
run a piece of code. with-mutex locks a mutex, evaluates its
body, and unlocks the mutex again, also when the body raises an error.
(use-modules (ice-9 threads))
(define counter 0)
(define counter-lock (make-mutex))
(define (increment-many n)
(do ((i 0 (+ i 1)))
((= i n))
(with-mutex counter-lock
(set! counter (+ counter 1)))))
(define (run-threads count thunk)
(let ((threads (map (lambda (i) (call-with-new-thread thunk))
(iota count))))
(for-each join-thread threads)))
(run-threads 4 (lambda () (increment-many 100000)))
(format #t "expected 400000, got ~a~%" counter)
(define balances (vector 500 500 500))
(define bank-lock (make-mutex))
(define (transfer! from to amount)
(with-mutex bank-lock
(when (>= (vector-ref balances from) amount)
(vector-set! balances from (- (vector-ref balances from) amount))
(vector-set! balances to (+ (vector-ref balances to) amount)))))
(define (random-transfers n state)
(lambda ()
(do ((i 0 (+ i 1)))
((= i n))
(transfer! (random 3 state) (random 3 state) (+ 1 (random 50 state))))))
(for-each join-thread
(map (lambda (seed)
(call-with-new-thread
(random-transfers 20000 (seed->random-state seed))))
'(1 2 3 4)))
(format #t "~a total ~a~%" balances
(+ (vector-ref balances 0) (vector-ref balances 1)
(vector-ref balances 2)))
The increment is now done under counter-lock, so no update is
lost and the count is exact. The bank example keeps three balances in a
vector. A transfer checks the balance and moves the money in one locked
step, so no thread sees a state in which the money has left one account
but not arrived in the other, and the total stays 1500. Each thread has its
own random state from the random
numbers article; the balances at the end depend on the order of the
transfers and vary between runs.
$ guile mutex.scm expected 400000, got 400000 #(796 594 110) total 1500
Condition variables
A thread often has to wait until another thread has produced something. A condition variable lets it sleep until it is signalled, instead of checking a variable in a busy loop.
(use-modules (ice-9 threads))
(define items '())
(define lock (make-mutex))
(define not-empty (make-condition-variable))
(define (put! item)
(with-mutex lock
(set! items (append items (list item)))
(signal-condition-variable not-empty)))
(define (take!)
(with-mutex lock
(let wait ()
(when (null? items)
(wait-condition-variable not-empty lock)
(wait)))
(let ((item (car items)))
(set! items (cdr items))
item)))
(define (consumer)
(let loop ((total 0) (count 0))
(let ((item (take!)))
(if (eq? item 'done)
(list count total)
(begin
(format #t "consumed ~a~%" item)
(loop (+ total item) (+ count 1)))))))
(define reader (call-with-new-thread consumer))
(for-each (lambda (n)
(usleep 50000)
(format #t "produced ~a~%" n)
(put! n))
'(3 1 4 1 5))
(put! 'done)
(format #t "items and sum: ~a~%" (join-thread reader))
The queue is a list guarded by lock. put! adds an
item and signals not-empty. take! waits while the
queue is empty: wait-condition-variable unlocks the mutex,
sleeps until a signal arrives, and locks the mutex again before it returns.
The loop checks the queue again after waking up, because another thread
may have taken the item first. The consumer thread processes numbers until
it takes the symbol done, and returns the count and sum of the
items. Queues are described in the
stacks, queues and trees
article.
$ guile queue.scm produced 3 consumed 3 produced 1 consumed 1 produced 4 consumed 4 produced 1 consumed 1 produced 5 consumed 5 items and sum: (5 14)
Parallel map
The (ice-9 threads) module also provides higher-level
procedures. par-map works like map but computes
the elements in parallel, and n-par-map limits the number of
threads.
(use-modules (ice-9 threads) (ice-9 format))
(define (fib n)
(if (< n 2)
n
(+ (fib (- n 1)) (fib (- n 2)))))
(define (timed label thunk)
(let* ((start (get-internal-real-time))
(result (thunk))
(secs (/ (- (get-internal-real-time) start)
internal-time-units-per-second)))
(format #t "~10a ~,3f s ~a~%" label (exact->inexact secs) result)))
(define inputs '(30 31 30 31 30 31 30 31))
(display (current-processor-count))
(newline)
(timed "map" (lambda () (map fib inputs)))
(timed "par-map" (lambda () (par-map fib inputs)))
(timed "n-par-map" (lambda () (n-par-map 2 fib inputs)))
current-processor-count is the number of cores available.
timed calls a thunk and prints the elapsed time with the
result, using the clock from the date and
time article. The eight Fibonacci numbers are independent, so they can
be computed at the same time. par-map is about three times
faster than map here, and n-par-map with two
threads lies in between. The results are in the order of the inputs. The
timings depend on the machine and on its load.
$ guile parallel.scm 8 map 0.136 s (832040 1346269 832040 1346269 832040 1346269 832040 1346269) par-map 0.046 s (832040 1346269 832040 1346269 832040 1346269 832040 1346269) n-par-map 0.067 s (832040 1346269 832040 1346269 832040 1346269 832040 1346269)
Futures
A future is a computation that may run in parallel with the
code that created it. future from (ice-9 futures)
starts it, and touch waits for its value. Futures run on a
pool of threads that Guile manages.
(use-modules (ice-9 futures))
(define (count-primes from to)
(define (prime? n)
(and (> n 1)
(let loop ((d 2))
(cond ((> (* d d) n) #t)
((zero? (remainder n d)) #f)
(else (loop (+ d 1)))))))
(let loop ((n from) (count 0))
(if (>= n to)
count
(loop (+ n 1) (if (prime? n) (+ count 1) count)))))
(define ranges
'((0 250000) (250000 500000) (500000 750000) (750000 1000000)))
(define futures
(map (lambda (range)
(future (count-primes (car range) (cadr range))))
ranges))
(display "futures started")
(newline)
(define counts (map touch futures))
(display counts)
(newline)
(display (apply + counts))
(newline)
(display (count-primes 0 1000000))
(newline)
count-primes counts the primes in a range by trial division.
The program splits the range up to a million into four parts and creates
a future for each. map over touch collects the
four counts. Primes thin out as numbers grow, so the later parts contain
fewer of them. The sum agrees with the count computed directly: there are
78,498 primes below a million.
$ guile futures.scm futures started (22044 19494 18700 18260) 78498 78498
Errors in threads
An error that is not handled inside a thread ends the thread: Guile
prints the error, and join-thread then returns no value. A
thread should therefore handle its own errors, as described in the
exceptions article, and return a value
that describes the failure.
(use-modules (ice-9 threads) (ice-9 futures) (ice-9 exceptions))
(define (parse-reading text)
(let ((n (string->number text)))
(if n
n
(error "not a number:" text))))
(define (safe-parse text)
(guard (e ((error? e)
(cons 'failed (exception-irritants e))))
(parse-reading text)))
(define threads
(map (lambda (text)
(call-with-new-thread (lambda () (safe-parse text))))
'("21.5" "n/a" "19")))
(display (map join-thread threads))
(newline)
(define f (future (parse-reading "--")))
(guard (e ((error? e)
(format #t "the future failed: ~a~%" (exception-irritants e))))
(touch f))
safe-parse catches the error of parse-reading
with guard and returns a list that starts with
failed, so the main thread receives a result from every
thread. A future behaves differently: an error raised in the future is
raised again by touch, in the thread that asks for the value,
where an ordinary guard can catch it.
$ guile errors.scm (21.5 (failed n/a) 19) the future failed: (--)
Source
Threads — GNU Guile Reference Manual
Futures — GNU Guile Reference Manual
In this article we have started threads and joined them for their
results, watched several threads interleave, lost updates in a race
condition and prevented it with a mutex, built a queue with a condition
variable, computed in parallel with par-map and futures, and
handled errors in threads. The closures
article explains the procedures that the threads run, and the
continuations article covers another
way of transferring control.
Author
List all Scheme tutorials.