Golang 面试题 (4) N个协程交替打印1-100
- 启动N个协程,共用一个外部变量计数器,计数器范围是1到100
- 开启N个有缓冲chan,chans[i]塞入数据代表协程i可以进行打印了,打印的数字就是计数器的数
- 协程i一直阻塞,直到chan[i]通道有数据可以拉,才打印
- func main() {
- gorutinenum := 5
- var chanslice []chan int
- exitchan := make(chan int)
-
- for i := 0; i < gorutinenum; i++ {
- chanslice = append(chanslice, make(chan int, 1))
- }
-
- res := 1
- j := 0
- for i := 0; i < gorutinenum; i ++ {
- go func(i int) {
- for {
- <-chanslice[i]
- if res > 100 {
- exitchan <- 1
- break
- }
-
- fmt.Println(fmt.Sprintf("gorutine%v:%v", i, res))
- res ++
-
- if j == gorutinenum-1 {
- j = 0
- }else {
- j ++
- }
- chanslice[j] <- 1
- }
- }(i)
- }
- chanslice[0] <- 1
-
- select {
- case <-exitchan:
- fmt.Println("end")
- }
- }




