dtmsaqtly798322992 2015-03-22 22:28
浏览 19
已采纳

如何退出频道范围/收集结果

I need to process several tasks concurrently and then "collect" the results. Below is the code I came up with but I'm wondering if it's the right way to do this(i.e idiomatic/ best practice) or if there is something wrong that I might miss.

package main

import "fmt"
import "sync"

func main() {
    // ch is the int provider. Cap is 99 but it should 
    // really be 3
    ch := make(chan int, 99)
    var wg sync.WaitGroup
    for i := 0; i < 3; i++ {
        wg.Add(1)
        go func(i int) {
            defer wg.Done()
            ch <- i
        }(i)
    }
    wg.Wait()
    for v := range ch {
        fmt.Println("consume ", v)
        if len(ch) == 0 {
            close(ch)
        }
    }
    fmt.Printf("All done")
}
  • 写回答

2条回答 默认 最新

  • douyulv6921 2015-03-22 23:07
    关注

    There's nothing wrong with that .. it works. However, it really should be the producers job to close the channel (not the consumer).

    To that end .. I would propose that you move the entire producer process into a goroutine and have that wait .. then close the channel:

    package main
    
    import "fmt"
    import "sync"
    
    func main() {
        ch := make(chan int, 3)
        var wg sync.WaitGroup
    
        go func() {
            for i := 0; i < 3; i++ {
                wg.Add(1)
                go func(i int) {
                    defer wg.Done()
                    ch <- i
                }(i)
            }
            wg.Wait()
            close(ch) // producer is now closing the channel
        }()
    
        // Consumer has the single responsibility of iterating over the channel
        for v := range ch {
            fmt.Println("consume ", v)
        }
        fmt.Printf("All done")
    }
    

    <kbd>See it in the Go Playground</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 我的数据无法存进链表里
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端