Skip to content

thread

Running code on several threads at once, with structured operations that always wait for every thread they start.

thread.join, thread.each and thread.workers are built into the compiler; import thread makes them available, and the module itself only adds cpus. Because each operation returns only when all its threads have finished, threads may borrow the caller’s variables. They may not hold &mut; shared changes go through Mutex<T> or Channel<T> (both in the prelude). These rules make data races a compile error.

Closures passed to threads list what they capture in brackets: [&data] borrows, [x] moves or copies.

Run two functions at once with join, which returns both results as a tuple:

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

Map a function over a Vec on every core with each. The results keep the input order:

import thread
let words = ["alpha", "be", "gamma"]
let sizes = thread.each(&words, fn(w: &Str) => w.len())
print(sizes.map(fn(n) => n.to_str()).join(" "))
5 2 5

Share a counter through a Mutex. The lock is held exactly while the function given to lock runs:

import thread
let counter = Mutex.new(0)
let items = (0..100).collect()
let _ = thread.each(&items, fn(unused i: &i64) -> i64 [&counter] => counter.lock(fn(c) -> i64 {
*c += 1
return *c
}))
print(counter.lock(fn(c) => *c))
100

A thread pool: one thread feeds a Channel, and workers(n, f) runs f(0) to f(n - 1) on their own threads, each taking jobs until the channel is closed and empty:

import thread
let jobs: Channel<i64> = Channel.new()
let (_, sums) = thread.join(fn() -> i64 [&jobs] {
for i in 1..101 {
jobs.send(i)
}
jobs.close()
return 0
}, fn() -> Vec<i64> [&jobs] => thread.workers(4, fn(unused w: i64) -> i64 [&jobs] {
let mut sum = 0
while true {
match jobs.recv() {
Some(n) => sum += n
None => break
}
}
return sum
}))
print(sums.len())
print(sums.iter().fold(0, fn(a: i64, b: &i64) => a + *b))
4
5050

Things to know:

  • If one side of join returns nothing, join returns just the other side’s result, not a tuple.
  • Functions given to threads may fail (fn() -> T ! E). The call then fails with their combined errors, so write try thread.join(...) or catch. Every thread still runs to the end. For join the error of the first argument wins; for each no new items start after a failure, and the error is the one from the lowest failing index, as a sequential loop would give. Other errors are dropped; to keep every outcome, catch inside the function and return an enum.
  • A closure written directly as an argument of join runs once, so it may move what it captured. Closures given to each and workers run many times and must clone what they capture by value.
  • each and workers start real threads. For tiny amounts of work per item, a plain loop is faster.
  • workers threads that block on a channel or socket do not starve each other, so n may be larger than cpus().
  • The predictable random generator is per thread; see random.seed.
import thread
pub fn cpus() -> i64

thread.join and thread.each are built into the compiler; this module adds helpers.

The number of cores the program can use. A good default for thread.workers when the work is CPU-bound:

import thread
let squares = thread.workers(thread.cpus(), fn(i: i64) => i * i)
print(squares.len() == thread.cpus())
true