Remove only works with the last peer of the list
ernestoalejo opened this issue · 0 comments
ernestoalejo commented
This code captures only the last iteration of the for loop. When the goroutines finally run the variable peer
has already changed to the last value.
// Asynchronously clear the key from all hot and main caches of peers
for _, peer := range g.peers.GetAll() {
// avoid deleting from owner a second time
if peer == owner {
continue
}
wg.Add(1)
go func() {
errs <- g.removeFromPeer(ctx, peer, key)
wg.Done()
}()
}
You can see the same efect here: https://play.golang.org/p/I82KNfRkqSP
Go vet will also highlight the error:
./prog.go:16:19: loop variable peer captured by func literal
The solution here is easy though. The smallest working change is to pass the peer as an argument to the goroutine: https://play.golang.org/p/0mNV3nSkGUy