Skip to content

std.thread

API summary (generated from the Beans source by npm run coverage): 1 package function.

std.thread runs a closure on a real operating-system thread. Each one is a full OS thread, not a green thread — for those, brew starts a fiber (Fibers and brew). It is a native module, built into the compiler and runtime.

import std.thread
FunctionReturnsWhat it does
thread.spawn(fn() -> T) -> Thread<T>Thread<T>run a closure on a new thread

The closure you pass may only capture Send values and must return a Send value. Send means “safe to move to another thread.” Move-only socket, HTTP, Bytes, File, and MMap owners can cross with an explicit fn() move(owner) { ... } capture. Plain class references and TLS handles stay local.

Thread<T> has two completion choices:

  • join() -> T: wait for the thread to finish and take its returned value.
  • detach(): let it finish independently and discard its returned value.
import std.io
import std.thread
fn main() {
let worker: Thread<int> = thread.spawn(fn() -> int {
var total: int = 0
for i in 0..1000 { total += i }
return total
})
let result: int = worker.join()
io.println(result) // 499500
}

spawn/join alone only pass a value out at the end. To share state while threads run, use the sync tools, which are builtin types documented in the builtin reference:

  • Mutex: lock around shared state.
  • Channel: send values between threads.
  • Atomic: lock-free single values.

See Ownership handles and Atomics.