golang 如何使用 channel 编排多个 goroutine 的执行顺序
func main() {
ch1 := make(chan struct{})
ch2 := make(chan struct{})
go func() {
fmt.Println("goroutine 1 is running")
ch1 <- struct{}{}
}()
go func() {
<-ch1
fmt.Println("goroutine 2 is running")
ch2 <- struct{}{}
}()
<-ch2
fmt.Println("all goroutines have finished")
}
在上面的代码中,我们创建了两个 struct{} 类型的 channel,然后启动了两个新的 goroutine。在第一个 goroutine 中,我们输出 “goroutine 1 is running”,然后向 ch1 发送一个空结构体。在第二个 goroutine 中,我们从 ch1 中接收一个值,然后输出 “goroutine 2 is running”,最后向 ch2 发送一个空结构体。最后,在主 goroutine 中,我们从 ch2 中接收一个值,然后输出 “all goroutines have finished”。
由于第二个 goroutine 在接收值之前会阻塞,所以它只有在第一个 goroutine 向 ch1 发送值之后才会继续执行。同样地,主 goroutine 在接收值之前也会阻塞,所以它只有在第二个 goroutine 向 ch2 发送值之后才会继续执行。因此,运行这段代码时,你会看到先输出 “goroutine 1 is running”,然后输出 “goroutine 2 is running”,最后输出 “all goroutines have finished”。