在Go语言中,可以使用单个Channel通过传递令牌的方式保证多个Goroutine按顺序同步输出。以下是具体实现方案:
package main
import (
"fmt"
"time"
)
func worker(ch chan string, id string, nextID string) {
for {
token := <-ch // 等待令牌
if token == id {
fmt.Println(id) // 执行输出
if nextID != "" { // 传递令牌给下一个
ch <- nextID
}
return // 当前Goroutine任务完成
} else {
ch <- token // 非当前令牌,放回Channel
}
}
}
func main() {
ch := make(chan string, 1)
ch <- "A" // 初始化令牌
// 启动三个Goroutine,按A->B->C顺序执行
go worker(ch, "A", "B")
go worker(ch, "B", "C")
go worker(ch, "C", "") // 最后一个不传递令牌
// 等待足够时间确保所有Goroutine执行完毕
time.Sleep(1 * time.Second)
}
此方案通过巧妙的令牌传递机制,实现了多Goroutine的同步顺序控制,是单Channel同步的经典应用场景。