其他分享
首页 > 其他分享> > golang通过errgroup单chan多个grouting通讯样例

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
}

 

标签:ch,err,int,样例,errgroup,chan,num,func,fmt
来源: https://www.cnblogs.com/quchunhui/p/16281159.html