私はgoroutineをforループ内に以下のように記述しました。私が望むのは、listofDevicesリスト内の各項目のゴルーチンを同時に実行することですが、このロジックはlistofDevicesリスト内の1つの項目についてのみgoroutineを実行しています。forループ内の同時ゴルーチン
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()
誰でもこの問題を解決するのに手伝ってもらえますか?ありがとうございます。
それはで使用される前に、ctx
変数名は、forループで上書きされている
go func(c context.Context) {
defer wg.Done()
pingOneMachine.Run(c)
}(ctx) // pass in the lexically scoped variable here
:
'wg.Add(len(listOfDevices))'ループが間違っているように見えるので、ループの前に移動してください。あるいは 'wg.Add(1)'と置き換えてください。 – ain
inchanとは何ですか?それはバッファされたチャンネルか、一定の読者を持つチャンネルですか? – kca
inchanは1の容量を持っているように見え、大きな値でプレイします。 –