Skip to content

Concurrency

Brass has structured concurrency: a call that starts threads returns only when all of them have finished. Because of that, threads can borrow the caller’s variables safely, and data races are compile errors.

import thread
fn count_primes(from: i64, to: i64) -> i64 {
let mut count = 0
for n in from..to {
let mut prime = n > 1
let mut d = 2
while d * d <= n {
if n % d == 0 {
prime = false
break
}
d += 1
}
if prime {
count += 1
}
}
return count
}
let (low, high) = thread.join(fn() => count_primes(0, 5000), fn() => count_primes(5000, 10000))
print(f"{low + high} primes below 10000")
let words = ["thread", "each", "keeps", "order"]
let lengths = thread.each(&words, fn(w: &Str) => w.len())
print(lengths.map(fn(n) => n.to_str()).join(" "))
1229 primes below 10000
6 4 5 5
  • thread.join(f, g) runs two functions at once and gives both results.
  • thread.each(&items, f) applies f to every item, spread over the cores, and keeps the order.
  • thread.workers(n, f) runs f(0) to f(n - 1), each on its own thread.

Threads cannot share &mut access. Shared changes go through a Mutex, which is locked exactly while a function runs, or a Channel, which moves values from one thread to another:

import thread
let total = Mutex.new(0)
thread.workers(4, fn(i: i64) [&total] {
total.lock(fn(t: &mut i64) [i] {
*t += i
})
})
print(f"{total.lock(fn(t: &mut i64) -> i64 => *t)}")
6