这是我的代码运行,但是当我尝试将 slice 的 valeu 更改为属性 count 时,该值不会改变。我更改值 ip 因为它们是内部的。我怎么说这段代码是运行的,他有更多其他功能可以发送电子邮件,但它们不会产生问题。func testeLink() { naves := []nave{ nave{"SC", "111.11.11.111", 0}, nave{"MA", "222.2.222.2", 0}, nave{"PE", "333.33.33.33", 0}} sliceLength := len(naves) var wg sync.WaitGroup wg.Add(sliceLength) for i := range naves { go func(nave nave) { out, _ := exec.Command("ping", nave.ip, "-c 1 -w 1").Output() //out, _ := exec.Command("ping", "192.168.0.111", "-c 1", "-i 3", "-w 10").Output() if strings.Contains(string(out), "0 received") || strings.Contains(string(out), "Received = 0") { fmt.Print(naves[i].count) nave.count++ fmt.Print(nave.count) fmt.Printf("A nave <%s> está OFFline \n", nave.name) if nave.count >= 3 { enviarEmail(nave.name) } } else { nave.count = 0 fmt.Printf("A nave <%s> está ONline \n", nave.name) } defer wg.Done() }(naves[i]) } wg.Wait()}func main() { for { testeLink() fmt.Println("Aguardando o tempo ...") time.Sleep(5 * time.Second) }}
1 回答
30秒到达战场
TA贡献1828条经验 获得超6个赞
你的 goroutine 是naves[i]
按值获取的,所以它的副本被传递给它。传递对它的引用:
go func(nave *nave) {...} (&naves[i])
或者,您可以简单地通过i
:
go func(i int) { // use naves[i] in the goroutine } (i)
- 1 回答
- 0 关注
- 153 浏览
添加回答
举报
0/150
提交
取消