package main

import (
    "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
        }
    }
}