多协程累加读写(尚硅谷GO语言)

【多协程累加读写(尚硅谷GO语言)】注解啥的都写里面了,大家有不懂的可以问我

package mainimport ( "fmt" )//定义计算的数值大小 var numMax int = 20000// 定义开启 read 协程的数量 var readMax int = 8// 存储定义的数值1,2,3,4,5........20000 var numchan chan int = make(chan int, numMax)// 存储计算结果 var reschan chan int = make(chan int, numMax)// 存储协程执行完毕后返回的个数 var endchan chan bool = make(chan bool, readMax)func main() { go writeNum()go readNum() go readNum() go readNum() go readNum()go readNum() go readNum() go readNum() go readNum()for { // 持续循环,判断结束信息是否都被添加 if len(endchan) == readMax { close(reschan) break } } // 循环遍历 index := 1 for x := range reschan { fmt.Printf("res[%d] = %d", index, x) fmt.Println() index++ }}// 写入数据 func writeNum() { for i := 1; i <= numMax; i++ { numchan <- i } close(numchan) }// 读取数据 func readNum() { // 持续循环计算 for { if len(numchan) > 0 { number := <-numchan sum := 0 for i := 1; i <= number; i++ { sum += i } reschan <- sum continue } //如果 reschan 的数据都被添加完毕 if len(reschan) == numMax { // 添加结束信息 endchan <- true //结束 break } } }

    推荐阅读