dpgua04022 2015-12-05 04:51
浏览 25

我如何使用通道知道循环启动的所有goroutine何时完成

I'm currently trying to range over a map to do concurrent database requests rather than synchronously, obviously because of the speed boost.

My problem is I have something like this:

var mainthreads = make(chan *mainthread)
var mainthreadsFetched = make(chan struct{})
for containerid := range containers {
    go func() {
        rows, err := db.Query("SELECT thread_id, belongs_to, thread_name, access_level FROM forum_mainthread WHERE belongs_to = ?", containerid)
        defer rows.Close()
        if err != nil {
            log.Println(err)
        }
        for rows.Next() {
            mainthread := &MainThread{}
            err := rows.Scan(&mainthread.MainThreadID, &mainthread.BelongsTo, &mainthread.ThreadName, &mainthread.AccessLevel)
            if err != nil {
                log.Println(err)
            }
            mainthreads <- mainthread
        }
    }()
    mainthreadsFetched <- struct{}{}
}

// Get all mainthreads
<-mainthreadsFetched
// Do other stuff after complete

Obviously mainthreadsFetched <- struct{}{} is being called almost instantly because the loop finishes faster than you can blink, how can I create a new channel per loop that will not block each new goroutine from starting, but rather let the loop start all goroutines and then send out on a channel when every goroutine is done.

  • 写回答

3条回答 默认 最新

  • dpv21589 2015-12-05 04:59
    关注

    Using sync.WaitGroup is a great solution, and the one usually used.

    Alternatively, you can receive on mainthreadsFetched len(containers) times, instead of just 1. That will guarantee that all go routines have completed. You'll need to move the send line to the end of the go routine (or, better, into a defer).

    Also, since containerid is in the for loop, its value changes. You need to pass it as a parameter to the go routine closure.

    评论

报告相同问题?

悬赏问题

  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch