XU XUv0.16.0

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 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)

    $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.

멀티코어 M:N 스케줄링 (0.14.4+ / 0.15.0)

Linux 및 macOS에서는 Xu 0.14.4부터 멀티코어 M:N 코루틴 스케줄링(#sync/pool)이 기본으로 활성화됩니다. Xu 0.15.0은 EventSet 드레인 라이브락을 수정하고 버퍼링된 채널을 최적화했으며 워커 상태 M에 캐시 라인 격리를 추가했습니다. 자세한 내용은 동시성 · M:N 멀티코어 스케줄러를 참고하세요.