douhuan1905 2019-05-22 08:43
浏览 31

如何从多个goroutine写入同一通道

I need several goroutines to write in the same channel. Then all the data is read in one place until all the goroutines complete the process. But I'm not sure how best to close this channel.

this is my example implementation:

func main() {
    ch := make(chan data)
    wg := &sync.WaitGroup{}
    for instance := range dataSet {
        wg.Add(1)
        go doStuff(ch, instance)
    }
    go func() {
        wg.Wait()
        close(ch)
    }()

    for v := range ch { //range until it closes
        //proceed v
    }
}

func doStuff(ch chan data, instance data) {
    //do some stuff with instance...
    ch <- instance
}

but I'm not sure that it is idiomatic.

  • 写回答

1条回答 默认 最新

  • 普通网友 2019-05-22 10:40
    关注

    As you are using WaitGroup and increase the counter at the time of starting new goroutine, you have to notify WaitGroup when a goroutine is finished by calling the Done() method. Also you have to pass the same WaitGroup to the goroutine. You can do it by passing the address of WaitGroup. Otherwise each goroutine will use it's own WaitGroup which will be on different scope.

    func main() {
        ch := make(chan data)
        wg := &sync.WaitGroup{}
        for _, instance := range dataSet {
            wg.Add(1)
            go doStuff(ch, instance, wg)
        }
        go func() {
            wg.Wait()
            close(ch)
        }()
    
        for v := range ch { //range until it closes
            //proceed v
        }
    }
    
    func doStuff(ch chan data, instance data, wg *sync.WaitGroup) {
        //do some stuff with instance...
        ch <- instance
    
        // call done method to decrease the counter of WaitGroup
        wg.Done()
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)