小编ger*_*rad的帖子

惯用的goroutine终止和错误处理

我有一个简单的并发用例,它让我疯狂,我无法找到一个优雅的解决方案.任何帮助,将不胜感激.

我想编写一种方法fetchAll,从远程服务器并行查询未指定数量的资源.如果任何提取失败,我想立即返回第一个错误.

我最初的,天真的实现,泄漏了goroutines:

package main

import (
  "fmt"
  "math/rand"
  "sync"
  "time"
)

func fetchAll() error {
  wg := sync.WaitGroup{}
  errs := make(chan error)
  leaks := make(map[int]struct{})
  defer fmt.Println("these goroutines leaked:", leaks)

  // run all the http requests in parallel
  for i := 0; i < 4; i++ {
    leaks[i] = struct{}{}
    wg.Add(1)
    go func(i int) {
      defer wg.Done()
      defer delete(leaks, i)

      // pretend this does an http request and returns an error
      time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
      errs <- fmt.Errorf("goroutine …
Run Code Online (Sandbox Code Playgroud)

channel go goroutine

9
推荐指数
3
解决办法
1万
查看次数

标签 统计

channel ×1

go ×1

goroutine ×1