如题
一个协程下发任务,发放到inChannel中
多个协程从inChannel中接收并处理数据,然后将结果汇总到outChannel中
一个协程从outChannel中接受处理结果

注意:
channel的关闭时机


func main() {
    // 一个线程将task写入到 inChannel 中,多个线程从inChannel中读取并处理,然后将结果写入到outchannel中
    var taskIds = []int{1, 2, 3, 4, 5}
    var inChannel = make(chan int, 1)
    var outChannel = make(chan int, 1)
    var wg = &sync.WaitGroup{}
    var wg2 = &sync.WaitGroup{}
    wg.Add(4)
    go func() {
        defer wg.Done()
        for _, v := range taskIds {
            inChannel <- v
        }
        close(inChannel)
    }()

    var processTask func(int)
    processTask = func(i int) {
        fmt.Println(i)
    }

    for i := 0; i < 3; i++ {
        go func() {
            defer wg.Done()
            for v := range inChannel {
                processTask(v)
                outChannel <- v
            }
        }()
    }

    wg2.Add(1)
    go func() {
        defer wg2.Done()
        for {
            v, ok := <-outChannel
            if !ok {
                break
            }
            fmt.Println("res", v)
        }
    }()

    wg.Wait()
    close(outChannel)
    wg2.Wait()
}

SyntaxError
199 声望19 粉丝