为了账号安全,请及时绑定邮箱和手机立即绑定

如何等待 go-routines 完成?

如何等待 go-routines 完成?

Go
陪伴而非守候 2022-07-11 16:40:21
下面是场景:inputCh := g(abc) // return <- chan []stringslice := make([]map[string][]string, 0)m := sync.Mutex{}for whatever := range inputCh {    go func(whatever []string) {        matches := f(xyz, whatever) // returns map[string][]string        m.Lock()        slice = append(slice, matches)        m.Unlock()    }(whatever)}z := merge(slice...)我们不知道的地方,何时inputCh关闭(close(inputCh))merge(slice...)我们只需要在所有 go-routines 完成和更新后调用slice不确定,如果sync.WaitGroup可以使用。如何确保只有在所有 go-routines 更新merge(slice...)后才被调用?slice
查看完整描述

2 回答

?
慕丝7291255

TA贡献1859条经验 获得超6个赞

使用sync.WaitGroup并检查通道何时关闭


var wg sync.WaitGroup


for {

    whatever, ok := <-inputCh

    if !ok { // check inputCh is close

        break

    }

    // add delta

    wg.Add(1)

    go func(whatever []string) {

        matches := f(xyz, whatever)

        m.Lock()

        slice = append(slice, matches)

        m.Unlock()

        // goroutine is done

        wg.Done()

    }(whatever)

}


// waits until all the goroutines call "wg.Done()"

wg.Wait()


查看完整回答
反对 回复 2022-07-11
?
呼如林

TA贡献1798条经验 获得超3个赞

您可以使用sync.WaitGroup.


// create a work group

var wg sync.WaitGroup

// add delta

wg.Add(len(inputCh))


slice := make([]map[string][]string, 0)

m := sync.Mutex{}

for whatever := range inputCh {

    go func(whatever []string) {

        matches := f(xyz, whatever) // returns map[string][]string

        m.Lock()

        slice = append(slice, matches)

        m.Unlock()

        // signal work group that the routine is done

        wg.Done()

    }(whatever)

}

// waits until all the go routines call wg.Done()

wg.Wait()


查看完整回答
反对 回复 2022-07-11
  • 2 回答
  • 0 关注
  • 195 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号