Docs/Advanced

Advanced

Async, tasks and workers

Choose non-blocking I/O, scoped tasks or isolated CPU workers.

About 16 minVersion: 0.10.1

Lazy futures and await

async fn returns a lazy Future<T>. await drives it to completion. Async file, process, HTTP and timer operations share a current-thread executor.

async.orvi
1async fn delayed(value: int) -> Result<int, string> {2    (await time.sleep_async(100))?3    return Ok(value * 2)4}56async fn main() -> Result<void, string> {7    let first = task.spawn(delayed(20))8    let second = task.spawn(delayed(21))9    print((await task.join(first))?)10    print((await task.join(second))?)11    return Ok()12}1314print(await main())

Structured tasks

task.spawn starts a future in the current lexical scope. The scope waits for unfinished children before it exits. join returns the result, cancel requests cooperative cancellation, and timeout applies a deadline.

CPU-parallel workers

worker.spawn runs isolated source on a bounded native thread pool. Values cross the boundary by serialization, so closures, modules, structs, futures, tasks, workers and cyclic values cannot be transferred.

worker.orvi
1async fn main() -> Result<void, string> {2    let handle = worker.spawn(3        "worker_input * worker_input",4        125    )6    let result = (await worker.join(handle))?7    print(result.value)8    return Ok()9}1011await main()

Ordered parallel.map

parallel.map applies isolated source to a list of inputs on the worker pool. Results preserve input order, and remaining work is cancelled after an item fails.

parallel.orvi
1async fn main() -> Result<void, string> {2    let results = (await parallel.map(3        "worker_input * worker_input",4        [2, 3, 4]5    ))?6    print(results)7    return Ok()8}910await main()