Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save daniellowtw/23b5a7017ea29decb20ea3a6d474eba0 to your computer and use it in GitHub Desktop.
Save daniellowtw/23b5a7017ea29decb20ea3a6d474eba0 to your computer and use it in GitHub Desktop.
Unsafe variable capture in loop
func Test(t *testing.T) {
a := map[int]int{
}
var b sync.Map
for i := 0; i < 2000; i++ {
a[i] = i
}
var wg sync.WaitGroup
wg.Add(2000)
for k, v := range a{
go func() {
b.Store(k, v)
wg.Done()
}()
}
wg.Wait()
for i := 0; i < 2000; i++ {
v, ok := b.Load(i)
if !ok {
t.Fatal("missing")
}
if v != i {
t.Fatal("wrong val")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment