Reputation: 1850
I am trying to loop a slice of function and then invoke every function in it. However I am getting strange results. Here is my code:
package main
import (
"fmt"
"sync"
)
func A() {
fmt.Println("A")
}
func B() {
fmt.Println("B")
}
func C() {
fmt.Println("C")
}
func main() {
type fs func()
var wg sync.WaitGroup
f := []fs{A, B, C}
for a, _ := range f {
wg.Add(1)
go func() {
defer wg.Done()
f[a]()
}()
}
wg.Wait()
}
I was thinking that it will invoke function A,B and then C but my output gets only Cs.
C
C
C
Please suggest whats wrong and the logic behind it. Also how can I get desired behavior.
Upvotes: 3
Views: 903
Reputation: 1313
Classic go gotcha :)
Official Go FAQ
for a, _ := range f {
wg.Add(1)
a:=a // this will make it work
go func() {
defer wg.Done()
f[a]()
}()
}
Your func() {}()
is a closure that closes over a
. And a
is a shared across all the go func
go routines because for loop reuses the same var (meaning same address in memory, hence same value), so naturally they all see last value of a
.
Solution is either re-declare a:=a
before closure (like above). This will create new var (new address in memory) which is then new for each invocation of go func
.
Or pass it in as parameter to the go function, in which case you pass a copy of value of a
like so:
go func(i int) {
defer wg.Done()
f[i]()
}(a)
You don't even need to have go routines this https://play.golang.org/p/nkP9YfeOWF for example demonstrates the same gotcha. The key here is 'closure'.
Upvotes: 6
Reputation: 768
The problem seems to be that you are not passing the desired value to the goroutine and the variable value is being taken from the outer scope. That being said, the range iteration finishes even before the first goroutine is executed and that is why you are always getting index a == 2, which is function C. You can test this if you simply put time.Sleep(100) inside your range, just to allow the goroutine to catch up with the main thread before continuing to the next iteration --> GO playground
for a, _ := range f {
wg.Add(1)
go func() {
defer wg.Done()
f[a]()
}()
time.Sleep(100)
}
Output
A
B
C
Although what you want to do is just simply pass a parameter to the goroutine which will make a copy for the function.
func main() {
type fs func()
var wg sync.WaitGroup
f := []fs{A, B, C}
for _, v := range f {
wg.Add(1)
go func(f fs) {
defer wg.Done()
f()
}(v)
}
wg.Wait()
}
Upvotes: 2