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()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"
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.
thread.yield
Section titled “thread.yield”Yields execution to the runtime scheduler.
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:
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()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. |