Skip to content

Thread

The @std/thread module provides lightweight concurrency helpers.

import thread from "@std/thread"
fn worker(name: string) void {
println("worker:", name)
}
thread.spawn(worker, "A")
thread.yield()
NameKindDescription
spawnfunctionRuns a function concurrently.
yieldfunctionYields execution to the scheduler.
PortalstructMessage-passing portal.

Runs a function in a new concurrent task.

The first argument must be a function. The remaining arguments are passed to that function.

import thread from "@std/thread"
fn greet(name: string) void {
println("Hello", name)
}
thread.spawn(greet, "Martin")

You can also pass an anonymous function value.

import thread from "@std/thread"
let job = fn(count: int) void {
println("count:", count)
}
thread.spawn(job, 5)

The arguments passed to spawn must match the function’s declared argument types.

Yields execution to the runtime scheduler.

import thread from "@std/thread"
thread.yield()

Portal is a message-passing structure for communication between concurrent work.

Create a portal with an optional capacity. If no capacity is given, the default is 16.

import thread from "@std/thread"
let portal = thread.Portal(16)

Send a message:

import thread from "@std/thread"
let portal = thread.Portal()
portal.send("hello")

Receive a message:

import thread from "@std/thread"
let portal = thread.Portal()
portal.send("hello")
let message = portal.receive()
println(message)

Receive with a timeout in milliseconds:

import thread from "@std/thread"
let portal = thread.Portal()
let message = portal.receive(1000)
println(message)

Close a portal:

import thread from "@std/thread"
let portal = thread.Portal()
portal.close()
NameDescription
closeCloses the portal.
sendSends a message into the portal.
receiveReceives a message, optionally with a timeout.