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()Exports
Section titled “Exports”| Name | Kind | Description |
|---|---|---|
spawn | function | Runs a function concurrently. |
yield | function | Yields execution to the scheduler. |
Portal | struct | Message-passing portal. |
thread.spawn
Section titled “thread.spawn”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.
thread.yield
Section titled “thread.yield”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()thread.Portal
Section titled “thread.Portal”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()Portal Methods
Section titled “Portal Methods”| Name | Description |
|---|---|
close | Closes the portal. |
send | Sends a message into the portal. |
receive | Receives a message, optionally with a timeout. |
Worker errors and ownership
Section titled “Worker errors and ownership”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.