Skip to content

Thread

The @std/thread module provides lightweight concurrency helpers.

import thread from "@std/thread"
let done = thread.Portal(1)
fn worker(name: string) void {
done.send("worker: " + name)
}
thread.spawn(worker, "A")
println(done.receive(5000))
done.close()
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"
let done = thread.Portal(1)
fn greet(name: string) void {
done.send("Hello, " + name)
}
thread.spawn(greet, "Martin")
println(done.receive(5000))
done.close()

You can also pass an anonymous function value.

import thread from "@std/thread"
let done = thread.Portal(1)
let job = fn(count: int) void {
done.send(count * 2)
}
thread.spawn(job, 5)
println(done.receive(5000))
done.close()

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

Yields execution to the runtime scheduler. This does not wait for a worker to finish. Use a portal for completion/results, as in the examples above.

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. A timeout raises a catchable error:

import thread from "@std/thread"
let portal = thread.Portal()
catch err {
let message = portal.receive(1000)
println(message)
}
if !isNil(err) {
println(err.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.

A worker’s asynchronous failure is reported separately; a caller’s catch around spawn does not wait for that failure. Communicate success or failure through a portal when the parent needs a result. Avoid relying on simultaneous unsynchronized writes to shared script objects.