XU XUv0.8.8
中文

Docs / Tutorial

10 · Coroutines and chan

Run independent tasks as coroutines and use chan to send values and collect results. These complete programs run with the local Xu compiler.

chan int{cap: 2} creates a channel with capacity 2. ch <- value sends a value and <-ch receives it; a standalone <- instead breaks a loop.

xu f(args) spawns a coroutine. Do not pass borrows of local variables into coroutines; these examples send integer values.

These three complete programs are also available in the homepage playground, whose WASM runner is written and compiled in Xu.

1 · Buffered send and receive

@main

fn main() int {
    messages := chan int{cap: 2}
    messages <- 7
    messages <- 35
    first := <-messages
    second := <-messages
    println(first + second)
    << 0
}

Download source

Run

xu run chan-buffered.xu

Output

42

2 · Collect results from multiple workers

@main

fn worker(id int, results chan int) {
    results <- id * 10
}

fn main() int {
    results := chan int{cap: 3}
    xu worker(1, results)
    xu worker(2, results)
    xu worker(3, results)

    mut total := 0
    for i in 0:3 {
        value := <-results
        total += value
    }
    println(total)
    << 0
}

Download source

Run

xu run chan-workers.xu

Output

60

3 · Producer and processing pipeline

@main

fn produce(output chan int) {
    for value in 1:6 {
        output <- value
    }
}

fn square(input chan int, output chan int) {
    for i in 0:5 {
        value := <-input
        output <- value * value
    }
}

fn main() int {
    numbers := chan int{cap: 2}
    squares := chan int{cap: 2}
    xu produce(numbers)
    xu square(numbers, squares)
    for i in 0:5 {
        value := <-squares
        println(value)
    }
    << 0
}

Download source

Run

xu run chan-pipeline.xu

Output

1
4
9
16
25

Worker completion order is not fixed, so the program receives all three results before summing them. The pipeline processes five inputs in their send order. Main waits for the expected results instead of relying on sleep.