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 一道python难题2
  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备