文档 / Tutorial
10 · 协程与 chan
通过协程执行独立任务,用 chan 传递值和汇总结果。这些完整程序使用本机 Xu 编译器运行。
chan int{cap: 2} 创建缓冲容量为 2 的信道。ch <- value 发送值,<-ch 接收值;这与单独使用的 <-(退出循环)不同。
xu f(args) 启动协程。不要把局部变量的借用传入协程;本例通过信道传递整数值。
这三个完整程序也已加入首页在线示例,可在 Xu 编写并编译的 WASM 运行器中直接运行。
1 · 带缓冲的发送与接收
@main
fn main() int {
messages := chan int{cap: 2}
messages <- 7
messages <- 35
first := <-messages
second := <-messages
println(first + second)
<< 0
}
运行
xu run chan-buffered.xu输出
422 · 多个 worker 汇总结果
@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
}
运行
xu run chan-workers.xu输出
603 · 生产者与处理流水线
@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
}
运行
xu run chan-pipeline.xu输出
1
4
9
16
25多个 worker 的完成顺序不保证固定,因此先接收三个结果再求和;流水线则按生产者的发送顺序处理五个输入。主函数接收完预定数量的结果后退出,不依赖 sleep 等待协程。