Skip to content

Concurrency

import thread gives two structured operations; each returns only when every thread it started has finished:

import thread
fn sum(v: &Vec<i64>, from: i64, to: i64) -> i64 {
let mut total = 0
for i in from..to {
total += v[i]
}
return total
}
let data = [1, 2, 3, 4, 5, 6]
let half = 3
let n = data.len()
let (a, b) = thread.join(fn() -> i64 [&data, half] => sum(&data, 0, half), fn() -> i64 [&data, half, n] => sum(&data, half, n))
print(a + b)
let words = ["one", "three"]
let sizes = thread.each(&words, fn(w: &Str) => w.len())
print(sizes[1])
21
5

thread.join runs two functions at once and returns both results (or, when one returns nothing, just the other’s); thread.each maps a function over a borrowed Vec on every core and keeps the order; thread.workers(n, f) runs f(0)..f(n-1) each on its own thread, all at once, and returns their results in order. Workers that block (on a channel or a socket) cannot starve each other, so workers plus a Channel is a thread pool:

import thread
let jobs: Channel<i64> = Channel.new()
thread.join(fn() [&jobs] {
for i in 0..10 {
jobs.send(i)
}
jobs.close()
}, fn() [&jobs] {
let _ = thread.workers(4, fn(unused w: i64) -> i64 [&jobs] {
let mut done = 0
while true {
match jobs.recv() {
Some(_) => done += 1
None => break
}
}
return done
})
})

A closure written directly as an argument of thread.join runs exactly once, so it may move what it captured by value (fn() [server] => serve(server)); other closures may run again and must clone. A short closure takes its result type and its errors from its expression. Because the caller waits, threads may borrow its variables freely. They may not hold &mut: changes are shared through

  • Mutex<T>: Mutex.new(v), m.lock(fn(v) => ...). The lock is held exactly while the function runs, so it cannot be left locked.
  • Channel<T>: ch.send(v) moves a value in, ch.recv() waits and gives None once the channel is closed and empty, ch.close().

Functions given to threads may fail; the call then fails with their combined error set, so try thread.join(...) works like any call. Every thread still runs to the end (a thread cannot be stopped safely, and what it borrows must stay valid until it does); for join the first failure in argument order is the error, for each no new items start after a failure and the error is the one from the lowest failing index, exactly what a sequential loop would give. Other results and errors are dropped. To keep every outcome, catch inside the function and return an enum.

Threads also may not capture C handles, since C libraries are not necessarily thread-safe; the standard library’s own handles (processes, sockets) can be moved to a thread. These rules make data races a compile error (ThreadSanitizer finds none in the tests). thread.cpus() reports the number of cores. A scope API that spawns any number of threads would need lifetime annotations to stay safe, which Brass leaves out; channels plus thread.each over worker indices cover that use.