Golang 并发多任务的同步问题

2021-04-27 11:03:51 +08:00
 winterssy

在 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")
	}
}
610 次点击
所在节点    问与答
1 条回复
keepeye
2021-04-27 11:22:39 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/773550

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX