Created
September 3, 2015 04:05
-
-
Save lanzafame/0e4abf4c5e989b67f211 to your computer and use it in GitHub Desktop.
Golang Gotcha Rendezvous iteration
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" | |
import "sync" | |
func main() { | |
twoNephews := []string{"Huey", "Dewey"} | |
threeNephews := append(twoNephews, "Louie") | |
var wg sync.WaitGroup | |
for _, nephew := range threeNephews { | |
wg.Add(1) | |
go func(who string) { | |
fmt.Println("Hello", who) | |
wg.Done() | |
}(nephew) | |
} | |
// Wait for all greetings to complete. | |
wg.Wait() | |
} | |
// Output: | |
// Hello Louie | |
// Hello Huey | |
// Hello Dewey |
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" | |
import "sync" | |
func main() { | |
twoNephews := []string{"Huey", "Dewey"} | |
threeNephews := append(twoNephews, "Louie") | |
var wg sync.WaitGroup | |
for _, nephew := range threeNephews { | |
wg.Add(1) | |
go func() { | |
fmt.Println("Hello", nephew) // the current value of nephew isn't captured by the goroutine | |
wg.Done() | |
}() | |
} | |
// Wait for all greetings to complete. | |
wg.Wait() | |
} | |
// Output: | |
// Hello Louie | |
// Hello Louie | |
// Hello Louie |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment