Created
June 16, 2022 13:57
-
-
Save daniellowtw/23b5a7017ea29decb20ea3a6d474eba0 to your computer and use it in GitHub Desktop.
Unsafe variable capture in loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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