Golang让协程交替输出

90design ·
最后一种方法,每次将数据发送到下一个个channel都会新建一个Goroutine,并没有控制Goroutine的数量,如果打印100个就会建立100Goroutine,这是我的修改方案,也可参见我的博客:[【豆仔gogo】练习题-golang交替打印数字的各种情况](http://beangogo.cn/2021/03/03/golang-%E4%BA%A4%E6%9B%BF%E6%89%93%E5%8D%B0/) ```go // 首发于博客:豆仔gogo: http://beangogo.cn package main import ( "fmt" ) func printNum(maxNum int, chanPre chan int, chanNext chan int, exit chan bool, id string) { for i := 0; i <= maxNum; i++ { num := <-chanPre select { case <-exit: return default: if num == maxNum+1 { exit <- true } else { fmt.Printf("id %s:%d\n", id, num) num += 1 chanNext <- num } } } } func main() { exit := make(chan bool) maxNum := 20 gNum := 5 if gNum < 2 { return } chanArr := make([]chan int, gNum) for i := 0; i < gNum; i++ { chanArr[i] = make(chan int) } for i := 0; i < gNum; i++ { if i != len(chanArr)-1 { go printNum(maxNum, chanArr[i], chanArr[i+1], exit, string(rune(i)+'A')) } else { go printNum(maxNum, chanArr[i], chanArr[0], exit, string(rune(i)+'A')) } } chanArr[0] <- 0 <-exit } ```
#1