golang通过errgroup单chan多个grouting通讯样例

直接上代码

package main

import (
    "errors"
    "fmt"
    "golang.org/x/sync/errgroup"
)

func main() {
    group := new(errgroup.Group)
    nums := []int{0, 1, -1, 2}

    ch := make(chan int)
    for _, num := range nums {
        num := num
        group.Go(func() error {
            err := output(ch, num)
            return err
        })
    }
    go func() {
        err := group.Wait()
        if err != nil {
            fmt.Println("get errors: ", err)
        } else {
            fmt.Println("all successfully")
        }
        close(ch)
    }()
    for re := range ch {
        fmt.Println("接收:", re)
    }
}

func output(ch chan int, num int) error {
    if num < 0 {
        return errors.New("数据小于0")
    }
    fmt.Println("写入:", num)
    ch <- num
    return nil
}

 

posted @ 2022-05-17 15:54  大墨垂杨  阅读(27)  评论(0编辑  收藏  举报