drgovyk64676 2019-02-05 12:35
浏览 41
已采纳

从多个go例程获取响应到数组

I need to fetch responses from multiple go routines and put them into an array. I know that channels could be used for this, however I am not sure how I can make sure that all go routines have finished processing the results. Thus I am using a waitgroup.

Code

func main() {
  log.Info("Collecting ints")
  var results []int32
  for _, broker := range e.BrokersByBrokerID {
      wg.Add(1)
      go getInt32(&wg)
  }
  wg.Wait()
  log.info("Collected")
}

func getInt32(wg *sync.WaitGroup) (int32, error) {
  defer wg.Done()

  // Just to show that this method may just return an error and no int32
  err := broker.Open(config)
  if err != nil && err != sarama.ErrAlreadyConnected {
    return 0, fmt.Errorf("Cannot connect to broker '%v': %s", broker.ID(), err)
  }
  defer broker.Close()

  return 1003, nil
}

My question

How can I put all the response int32 (which may return an error) into my int32 array, making sure that all go routines have finished their processing work and returned either the error or the int?

  • 写回答

2条回答 默认 最新

  • duanpanhuo0618 2019-02-05 13:27
    关注

    I also believe you have to use channel, it must be something like this:

    package main
    
    import (
        "fmt"
        "log"
        "sync"
    )
    
    var (
        BrokersByBrokerID = []int32{1, 2, 3}
    )
    
    type result struct {
        data string
        err string // you must use error type here
    }
    
    func main()  {
        var wg sync.WaitGroup
        var results []result
        ch := make(chan result)
    
        for _, broker := range BrokersByBrokerID {
            wg.Add(1)
            go getInt32(ch, &wg, broker)
        }
    
        go func() {
            for v := range ch {
                results = append(results, v)
            }
        }()
    
        wg.Wait()
        close(ch)
    
        log.Printf("collected %v", results)
    }
    
    func getInt32(ch chan result, wg *sync.WaitGroup, broker int32) {
        defer wg.Done()
    
        if broker == 1 {
            ch <- result{err: fmt.Sprintf("error: gor broker 1")}
            return
        }
    
        ch <- result{data: fmt.Sprintf("broker %d - ok", broker)}
    }
    

    Result will look like this:

    2019/02/05 15:26:28 collected [{broker 3 - ok } {broker 2 - ok } { error: gor broker 1}]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波