go - Wrapping a function call into a closure when using goroutines -
this question has answer here:
wrapping function call closure leads unexpected behaviour when using goroutines.
consider 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) { i:=0; < 3; i++{ log.printf("worker %d woke up! \n", worker) block() } wg.done() } func main() { i:=0; < workernum; i++ { //go func() { startworker(i) }() go startworker(i) } wg.add(workernum) wg.wait() }
test here: http://play.golang.org/p/nmlntkbwvf
one can see wrapping startworker(i)
func() { startworker(i) }()
results in calling 5-th worker.
it looks there wrong in way how closures capture variables outer scope. why happening? closures use pass-by-reference way passing outer variables instead of pass-by-value?
that's how closures in languages work, if want way, have isolate variable.
go func(i int) { startworker(i) }(i)
Comments
Post a Comment