Threads and concurrency
std.thread, tasks, channels, mutexes, condition variables, semaphores and atomics.
std.thread wraps the compiler's thread, channel and synchronisation builtins in
small classes. The builtins are raw integer handles; the module gives them names
and types.
Tasks
import { spawn, taskCount, currentId, sleep } from std.thread
fn worker(n: int) {
sleep(1)
println("worker {n} on thread {currentId()}")
}
fn main() {
println("tasks before {taskCount()}")
let t1 = spawn(fn() { worker(1) })
let t2 = spawn(fn() { worker(2) })
t1.join()
t2.join()
println("tasks after {taskCount()}")
}
| Function | Signature |
|---|---|
spawn |
spawn(body: fn()) -> Task |
taskCount |
taskCount() -> int |
currentId |
currentId() -> int |
sleep |
sleep(ms: int) |
yieldNow |
yieldNow() |
The body passed to spawn must be a zero-argument function, a closure, if it
captures anything. The runtime reads the function object's code address, so
anything else would be an invalid call.
Task member |
Signature |
|---|---|
id |
id() -> int |
join |
join() -> bool |
finished |
finished() -> bool |
message |
message() -> string? |
join blocks until the task finishes. message returns whatever the task's
harness recorded, or none.
Channels
Channels carry int values. The element type is int in both directions, a
string or a list never reaches the runtime, so box them yourself if you need
more than an integer.
A receiver must not block on recv after the sender is gone, so poll with
tryRecv and check closed:
import { Channel, spawn, sleep } from std.thread
fn producer(ch: Channel) {
for (i in 1..4) {
ch.send(i)
}
ch.close()
}
fn main() {
let ch = Channel(8)
spawn(fn() { producer(ch) })
var done = false
while (!done) {
match (ch.tryRecv()) {
case some(v) -> { println("received {v}") }
case none -> {
if (ch.closed()) {
done = true
} else {
sleep(1)
}
}
}
}
println("drained")
}
for (i in 1..4) walks 1, 2, 3, the upper bound is exclusive, and needs
sleep imported for the polling loop above.
| Member | Signature | Effect |
|---|---|---|
send |
send(v: int) |
Block until there is room |
trySend |
trySend(v: int) -> bool |
Send without blocking |
recv |
recv() -> int |
Block for a value; errors if closed and empty |
tryRecv |
tryRecv() -> int? |
none when nothing is buffered |
close |
close() |
Close the channel |
closed |
closed() -> bool |
Whether it is closed |
cap |
cap() -> int |
Capacity |
len |
len() -> int |
Buffered count |
recv is a definite value: receiving from a closed, empty channel is a loud
error rather than a silent none. Use tryRecv when you need to poll, and
closed to distinguish "drained" from "still producing".
Mutexes and condition variables
import { Mutex, CondVar, spawn, sleep } from std.thread
class Counter {
var m: Mutex
var cv: CondVar
var n: int
constructor() {
this.m = Mutex()
this.cv = CondVar()
this.n = 0
}
fn increment() {
this.m.lock()
this.n += 1
this.m.unlock()
}
fn value() -> int {
this.m.lock()
let v = this.n
this.m.unlock()
return v
}
}
fn main() {
let c = Counter()
for (i in 0..4) {
spawn(fn() { c.increment() })
}
sleep(10)
println("count {c.value()}")
}
Mutex member |
Signature |
|---|---|
lock |
lock() |
tryLock |
tryLock() -> bool |
unlock |
unlock() |
CondVar member |
Signature |
|---|---|
wait |
wait(m: Mutex) |
signal |
signal() |
broadcast |
broadcast() |
There is no defer in PickleScript, so a lock / unlock pair is not
unwind-safe. Keep the critical section small and do not call anything that can
fail inside it.
Semaphores and atomics
import { Semaphore, AtomicInt } from std.thread
fn main() {
let sem = Semaphore(2)
sem.acquire(1)
sem.release(1)
match (sem.tryAcquire(1)) {
case true -> { println("acquired") }
case false -> { println("would block") }
}
let a = AtomicInt(0)
println(a.load()) // 0
a.store(5)
println(a.add(3)) // 8
println(a.cas(8, 10)) // true, succeeded
println(a.load()) // 10
}
Semaphore member |
Signature |
|---|---|
acquire |
acquire(n: int) |
tryAcquire |
tryAcquire(n: int) -> bool |
release |
release(n: int) |
AtomicInt member |
Signature | Returns |
|---|---|---|
load |
load() -> int |
the current value |
store |
store(value: int) |
, |
add |
add(delta: int) -> int |
the value before the addition |
cas |
cas(expected: int, value: int) -> bool |
whether the swap happened |
add returns the previous value, not the new one. cas is compare-and-swap: it
stores value only if the current value equals expected.
import { AtomicInt } from std.thread
fn main() {
let a = AtomicInt(0)
println(a.add(3)) // 0, the old value
println(a.load()) // 3
println(a.cas(3, 10)) // true
println(a.cas(999, 1)) // false, no swap
println(a.load()) // 10
}
Once
A one-shot initialiser:
import { Once } from std.thread
fn main() {
let o = Once()
println(o.done()) // false
println(o.run(fn() { println("initialising") })) // true, ran
println(o.done()) // true
println(o.run(fn() { println("never runs") })) // false
}
run returns whether the body actually ran, which makes it easy to observe
from several threads without a race.
Channels carry int
Channel is a bounded queue of int, created with a capacity and closed by
going out of scope:
let c = Channel<int>(8)
c.send(42)
let v = c.recv() // 42
For structured payloads, send an int handle and keep the data in a shared
collection behind a Mutex.
