std.task
Tasks: running functions at the same time, and channels between them.
import std.task
let a = task.spawn(fn() -> i64 { return slow_sum(1) })
let b = task.spawn(fn() -> i64 { return slow_sum(2) })
print(a.join() + b.join())
let lines: task.Channel[string] = task.channel()
task.detach(fn() {
lines.send("hello")
lines.close()
})
print(lines.receive()) // Some("hello")Every task runs on its own thread. Tasks share no changeable memory: values are copied (lazily, when one side changes them), so a task never sees another task change something. They work together through channels and join.
Types
struct Task
pub struct Task[T] {
// and private fields
}A running task whose function returns a T.
Methods
pub fn join(self) -> TWaits for the task to finish and returns its result. A task is joined once.
struct Channel
pub struct Channel[T] {
// and private fields
}A channel carries values of one type between tasks. Copies of a channel refer to the same channel.
Methods
pub fn send(self, value: T) -> boolQueues a value for a receiver. False when the channel is closed.
pub fn receive(self) -> Option[T]The next value, waiting until there is one. None once the channel is closed and every value sent before was received.
pub fn close(self)Ends the channel: send returns false from now on, and receive returns None once the values already sent are received.
Functions
fn spawn
pub fn spawn[T](f: fn() -> T) -> Task[T]Runs f on a new task.
fn detach
pub fn detach(f: fn())Runs f on a new task that is never joined: a request handler or a background job.
fn channel
pub fn channel[T]() -> Channel[T]A new channel without a size limit.
fn bounded
pub fn bounded[T](capacity: i64) -> Channel[T]A new channel whose send waits while capacity values are queued.