← All examples

Concurrency

Spawn background work and communicate over a channel. Each spawned function runs in its own isolated VM.

import thread

// A buffered channel carrying messages between tasks
let ch = thread.channel.new(1)

thread.core.spawn(fn() {
    thread.channel.send(ch, "hello from a goroutine")
})

let msg = thread.channel.recv(ch)   // blocks until a value arrives
println(msg)

Or run a task and await its result with a future:

import thread
import time

let future = thread.async.run(fn() {
    time.timer.sleep(100)
    return "done"
})

println(thread.async.await(future))   // "done"

Because tasks don’t share mutable state by default, use runtime.core.share / runtime.core.fetch (guarded by a thread.mutex when needed) to coordinate.

#concurrency#backend · View as Markdown