2017-01-03 33 views
1

我已經在循環中寫入goroutine,如下所示。我想要的是同時爲listofDevices列表中的每個項目執行goroutine,但是此邏輯正在爲listofDevices列表中的一個項目運行goroutine。for循環中的併發goroutines

for _, ip := range listOfDevices { 
      inChan <- types.NewNotification(time.Now(), "/cloudtracer/status", nil, 
        &map[key.Key]interface{}{ 
          key.New(ip): types.Pointer{Pointer: "/cloudtracer/status/" + ip}, 
        }) 
      pingOneMachine := probe.NewPing(ip, 2*time.Second, inChan) 
      // For now stopping the probe after few minutes. This will change later 
      ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) 
      defer cancel() 

      wg.Add(len(listOfDevices)) 
      go func() { 
        defer wg.Done() 
        pingOneMachine.Run(ctx) 
      }() 
    } 
    wg.Wait() 

任何人都可以幫助我解決這個問題嗎? 在此先感謝。

+7

'wg.Add(len(listOfDevices))'在循環中似乎是錯誤的,在循環之前移動它。或者用'wg.Add(1)'替換它。 – ain

+2

什麼是inchan定義爲?它是一個緩衝頻道還是一個帶有恆定閱讀器的頻道? – kca

+0

它看起來像inchan有1的容量,發揮更大的價值。 –

回答

-1

做到像以下

for ;;{ 
     wg.Add(1) 
     go func(){ 
      defer wg.Done() 
     } 
    } 
    wg.Wait() 
+0

它不是以這種方式工作。 – supriya

0

嘗試使用夠程關閉

  go func(c context.Context) { 
        defer wg.Done() 
        pingOneMachine.Run(c) 
      }(ctx) // pass in the lexically scoped variable here 

也就是說,ctx變量名稱在for循環它在使用之前被覆蓋goroutine(因爲變量在詞彙範圍上),請參閱此問題以獲得很好的解釋Why does Golang handle closures differently in goroutines?

基本上變量被引用傳遞:

這意味着,從「外部」範圍封蓋中引用的任何變量不是副本,但實際上的參考。

0
for ;;{ 
    wg.Add(1) 
    go func(ip string){ 
     defer wg.Done() 
    }(ip) 
} 
wg.Wait() 

它的工作在所有的IP地址建立一個平行的夠程。