我已经编写了 go 代码来独立调用多个 http 请求并组合结果。
有时组合方法中缺少值。
func profile(req *http.Request) (UserMe, error, UserRating, error) {
wgcall := &sync.WaitGroup{}
uChan := make(chan ResUser)
rChan := make(chan ResRating)
// variable inits
var meResp UserMe
var ratingResp UserRating
go func() {
res := <-uChan
meResp = res.Value
}()
go func() {
res := <-rChan
ratingResp = res.Value
}()
wgcall.Add(2)
go me(req, wgcall, uChan)
go rate(req, wgcall, rChan)
wgcall.Wait()
logrus.Info(meResp) // sometimes missing
logrus.Info(ratingResp) // sometimes missing
return meResp, meErr, ratingResp, ratingErr
}
Run Code Online (Sandbox Code Playgroud)
但是 me 和 rating 调用按预期从 api 请求返回值。
func me(req *http.Request, wg *sync.WaitGroup, ch chan ResUser) {
defer wg.Done()
// http call return value correclty
me := ...
ch <- ResUser{
Value := // value from rest
}
logrus.Info(fmt.Sprintf("User calls %v" , me)) // always return the values
close(ch)
}
func rate(req *http.Request, wg *sync.WaitGroup, ch chan ResRating) {
defer wg.Done()
// make http call
rating := ...
ch <- ResRating{
Value := // value from rest
}
logrus.Info(fmt.Sprintf("Ratings calls %v" , rating)) // always return the values
close(ch)
}
Run Code Online (Sandbox Code Playgroud)
问题是:配置文件功能上的 meResp 和 ratingResp 始终无法获取值。有时只有 meResp 或 ratingResp,有时两者都符合预期。
但是 me 和 rate 函数总是调用获取值。
请帮我解决这个问题吗?
您的代码中存在竞争条件。
有没有障碍,以确保在该够程profile方法,从阅读uChan和rChan已填充的变量meResp和ratingResp 之前你返回profile。
您可以通过删除通道的使用和在profile. 相反,只需直接填充响应值。在这种情况下,使用通道或 goroutine 读取它们没有任何好处,因为您只想发送一个值,并且您要求两个 HTTP 调用产生的值在返回之前都存在。
您可以通过修改me和rate接收指向写入其输出的位置的指针来实现此目的,或者通过使用一个小函数包装它们的调用,该函数接收它们的输出值并将该值填充到profile. 重要的是,WaitGroup只应信号后,该值已被填充:
wgcall := &sync.WaitGroup{}
var meResp UserMe
var ratingResp RatingMe
wgcall.Add(2)
// The "me" and "rate" functions should be refactored to
// drop the wait group and channel arguments.
go func() {
meResp = me(req)
wgcall.Done()
}()
go func() {
ratingResp = rate(req)
wgcall.Done()
}()
wgcall.Wait()
// You are guaranteed that if "me" and "rate" returned valid values,
// they are populated in "meResp" and "ratingResp" at this point.
// Do whatever you need here, such as logging or returning.
Run Code Online (Sandbox Code Playgroud)