Skip to content

Concurrency

Threading lives in four standard library modules: threads, sync, channels and atomic. They need POSIX threads.

threads.spawn runs a function on a new thread and returns a handle. threads.join waits for it.

import @threads
do worker() {
println("hello from a thread")
}
do main() {
mut handle = threads.spawn(()worker)
threads.join(handle)
}

A channel is a buffered queue. Channels carry i64 values only.

import @channels
do main() {
mut ch = channels.open(4)
channels.send(ch, 10)
channels.send(ch, 20)
mut first = channels.receive(ch)
mut second = channels.receive(ch)
println(first + second)
channels.close(ch)
}
import @sync
do main() {
mut lock = sync.mutex()
sync.lock(lock)
println("inside the critical section")
sync.unlock(lock)
sync.destroy(lock)
}

atomic operates on ^i64 pointers without a lock. add returns the previous value.

import @atomic
do main() {
mut counter i64 = 0
mut previous = atomic.add(addr(counter), 5)
println("${previous} -> ${atomic.load(addr(counter))}")
}