
通过 channel 控制多个 goroutine 顺序执行
在 go 语言中,可以通过 channel 实现多个 goroutine 的顺序执行。这里介绍一种改进的方法,只使用一个 channel 来控制四个 goroutine 顺序执行"hello world"。
改进代码:
func channelShunxu() {
ch1 := make(chan int, 1) // 带缓冲的 Channel,容量为 1
ch1 <- 1 // 初始发送一个值到 Channel,触发顺序执行
Loop:
for {
select {
case value := <-ch1: // 接收 Channel 中的值
switch value {
case 1:
go printHello1(ch1) // 依次执行 Goroutine,并发送下一个值到 Channel
case 2:
go printSpace1(ch1)
case 3:
go printWorld1(ch1)
case 4:
go printLn1(ch1)
case 5:
close(ch1) // 关闭 Channel,结束顺序执行
break Loop
}
}
}
// 这里休息一秒,否则主 Goroutine 可能在子 Goroutine 执行前退出
time.Sleep(time.Second * 1)
}
func printHello1(ch1 chan int) {
fmt.Print("hello")
ch1 <- 2 // 发送下一个值到 Channel
}
func printSpace1(ch1 chan int) {
fmt.Print(" ")
ch1 <- 3 // 发送下一个值到 Channel
}
func printWorld1(ch1 chan int) {
fmt.Print("world")
ch1 <- 4 // 发送下一个值到 Channel
}
func printLn1(ch1 chan int) {
fmt.Println("")
ch1 <- 5 // 发送结束值到 Channel
}改进方法详解:
通过这种改进方法,我们可以通过一个 channel 控制多个 goroutine 的顺序执行,简化了代码逻辑。
以上就是如何使用一个 Channel 控制多个 Goroutine 顺序执行 "hello world"?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号