gpt4 book ai didi

go - 在 Go 中使用 WaitGroup 和 channel

转载 作者:行者123 更新时间:2023-12-01 22:43:10 24 4
gpt4 key购买 nike

我正在使用调用许多 Web 服务的 Go 开发 cargo 服务,但我不确定如何实现并发模型。这种方法刚刚奏效,但有时它会锁定。我相信 channel 和 WaitGroup 存在一些问题。我真的需要使用 WaitGroups 或者只有 channel 才能锁定例程。

// Call carriers quote webservice
var wg sync.WaitGroup
error := make(chan error)
quote := make(chan []freight.Quote)
for _, c := range carriers {
go c.Quote(&wg, obj, quote, error)
}
wg.Wait()

// Collect the results
quotes:= make([]freight.Quote, 0)
for i := 1; i < len(carriers); i++ {
err := <-error
quoteAws:= <-quote

if err != nil {
log.Println(err)
}
if quoteAws != nil {
quotes= append(quotes, quoteAws...)
}
}
close(error)
close(quote)

func (carrier CarrierA) Quote(wg *sync.WaitGroup, obj Volume, quotes chan []Quote, err chan error)
{
// Deal with waitgroup
wg.Add(1)
defer wg.Done()

// Quote the freigth
err <- nil
quotes <- quotesResult
return
}

最佳答案

使用 slice 来收集错误和引号。使用 WaitGroup 来等待 goroutine 完成。

errs := make([]error, len(carriers))
quotes := make([]freight.Quote, len(carriers))
var wg sync.WaitGroup
for i, c := range carriers {
wg.Add(1)
go func(i int, c Carrier) {
defer wg.Done()
quotes[i], errs[i] = c.Quote(args)
}(i, c)
}
wg.Wait()

关于go - 在 Go 中使用 WaitGroup 和 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63366250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com