V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
winterssy
V2EX  ›  问与答

Golang 并发多任务的同步问题

  •  
  •   winterssy · 2021-04-27 11:03:51 +08:00 · 608 次点击
    这是一个创建于 1112 天前的主题,其中的信息可能已经有所发展或是发生改变。

    在 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 条回复    2021-04-27 11:22:39 +08:00
    keepeye
        1
    keepeye  
       2021-04-27 11:22:39 +08:00   ❤️ 1
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1142 人在线   最高记录 6547   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 18:40 · PVG 02:40 · LAX 11:40 · JFK 14:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.