Created
June 27, 2018 12:03
-
-
Save bingoohuang/91a3c8d60e52cd32f309d39aa55c81a1 to your computer and use it in GitHub Desktop.
This file contains 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
package main | |
import ( | |
"fmt" | |
"sync" | |
) | |
// more to see https://github.com/golang/go/wiki/CommonMistakes | |
func main() { | |
m := []string{"a", "b", "c", "d"} | |
var wg sync.WaitGroup | |
// Buggy way, output closure v:dddd | |
fmt.Print("closure v:") | |
wg.Add(len(m)) | |
for _, v := range m { | |
go func() { | |
defer wg.Done() | |
fmt.Print(v) | |
}() | |
} | |
wg.Wait() | |
fmt.Println() | |
// Buggy way, output go func v:dddd | |
fmt.Print("go func v:") | |
wg.Add(len(m)) | |
for _, v := range m { | |
go trap1(&wg, &v) | |
} | |
wg.Wait() | |
fmt.Println() | |
// Right way, output closure v:dcba | |
fmt.Print("closure v:") | |
wg.Add(len(m)) | |
for _, v := range m { | |
go func(k string) { | |
defer wg.Done() | |
fmt.Print(k) | |
}(v) | |
} | |
wg.Wait() | |
fmt.Println() | |
// Right way, output: go func v:dcba | |
fmt.Print("go func v:") | |
wg.Add(len(m)) | |
for _, v := range m { | |
v1 := v | |
go trap1(&wg, &v1) | |
} | |
wg.Wait() | |
fmt.Println() | |
} | |
func trap1(wg *sync.WaitGroup, name *string) { | |
defer wg.Done() | |
fmt.Print(*name) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment