在 Go 中使用 WaitGroup 和通道
Using WaitGroup and channels in Go
我正在使用调用许多 Web 服务的 Go 开发货运服务,但我不确定如何实现并发模型。这种方法刚刚起作用,但有时会锁定。我相信渠道和 WaitGroup 存在一些问题。我确实需要使用 WaitGroups,或者只有通道足够才能锁定例程。
// 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
}
使用切片收集错误和引用。使用等待组等待 goroutines 完成。
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()
我正在使用调用许多 Web 服务的 Go 开发货运服务,但我不确定如何实现并发模型。这种方法刚刚起作用,但有时会锁定。我相信渠道和 WaitGroup 存在一些问题。我确实需要使用 WaitGroups,或者只有通道足够才能锁定例程。
// 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
}
使用切片收集错误和引用。使用等待组等待 goroutines 完成。
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()