在 main goroutine 中循环创建 goroutine 发起请求,只要有一个 goroutine 请求成功就表示成功,结束其它 goroutines 并退出循环,循环结束请求都失败才表示失败。如何优雅的等待并获取结果?参考代码:
func doRequest(ctx context.Context, i int) error {
panic("implement me!")
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var result int
resultCh := make(chan int)
go func() {
result = <-resultCh
cancel()
}()
limiter := make(chan struct{}, 16)
var wg sync.WaitGroup
loop:
for i := 1; i <= 9999; i++ {
select {
case <-ctx.Done():
break loop
default:
}
limiter <- struct{}{}
wg.Add(1)
go func(i int) {
if doRequest(ctx, i) == nil {
resultCh <- i
}
wg.Done()
<-limiter
}(i)
}
wg.Wait()
time.Sleep(100 * time.Millisecond) // 等待结果,除了 sleep 有没有更好的办法?
if result != 0 {
log.Print(result)
} else {
log.Print("FAIL")
}
}
1
keepeye 2021-04-27 11:22:39 +08:00 1
|