GO语言面试题目,使用3个协程按照顺序从1打印到100
稍微把题目拓展了下,使用N个协程 打印M个数,应该很好理解,创建一个N个协程的列表,然后每打印一个数,就传到下一个chan中,一次循环
package main
import (
"fmt"
"sync"
)
func printNum(index int, chanNums []chan int, wg *sync.WaitGroup, maxNum int, numGoruntine int) {
for {
num := <-chanNums[index]
if num <= maxNum {
fmt.Println("current goruntine num: ", index, num)
}
if num < maxNum {
chanNums[(index+1)%numGoruntine] <- (num + 1)
}
if num+numGoruntine > maxNum {
break
}
}
wg.Done()
}
func printNums(maxNum int, numGoruntine int) {
var chanList []chan int
var wg sync.WaitGroup
wg.Add(numGoruntine)
for i := 0; i < numGoruntine; i++ {
chanList = append(chanList, make(chan int))
}
for i := 0; i < numGoruntine; i++ {
go printNum(i, chanList, &wg, maxNum, numGoruntine)
}
chanList[0] <- 1
fmt.Println("done")
wg.Wait()
}
func main() {
printNums(100, 3)
}