Concurrency
Pyr has built-in green threads and channels. Spawn creates lightweight tasks scheduled cooperatively by the runtime, and bounded channels provide safe communication between them.
spawn creates a green thread (task). Tasks are cooperatively scheduled.
|
fn worker(id: int) {
println("worker {id} done")
}
|
channel(n) creates a bounded channel. .send() and .recv() block when full or empty.
|
fn producer(ch, n: int) {
for i in range(n) {
ch.send(i)
}
}
|
await_all waits for multiple tasks and collects their results into an array.
|
fn compute(x: int) -> int = x * x
fn main() {
spawn { worker(1) }
spawn { worker(2) }
ch = channel(4)
spawn { producer(ch, 4) }
for i in range(4) {
println(ch.recv())
}
results = await_all(
spawn { compute(3) },
spawn { compute(4) }
)
println(results)
}
|
|
$ pyr run concurrency.pyr
worker 1 done
worker 2 done
0
1
2
3
[9, 16]
|