This question already has an answer here:
Wrapping a function call into a closure leads to an unexpected behaviour when using goroutines.
Consider the following example:
package main
import (
"log"
"sync"
"time"
)
var workerNum = 5
var wg sync.WaitGroup
func block() {
dur := 300 * time.Millisecond
//time.Sleep()
select {
case <- time.After(dur): {}
}
}
func startWorker(worker int) {
for i:=0; i < 3; i++{
log.Printf("Worker %d woke up!
", worker)
block()
}
wg.Done()
}
func main() {
for i:=0; i < workerNum; i++ {
//go func() { startWorker(i) }()
go startWorker(i)
}
wg.Add(workerNum)
wg.Wait()
}
Test it here: http://play.golang.org/p/nMlnTkbwVf
One can see that wrapping startWorker(i)
into func() { startWorker(i) }()
results in calling only the 5-th worker.
It looks like there is something wrong in the way how closures capture variables from the outer scope. Why is this happening? Do closures use pass-by-reference way for passing outer variables instead of pass-by-value?
</div>