Hello everybody, I’m a rookie starting learning Go. And I have a question about my demo. I can’t understand why my output will be that.In my opinion, the outputs shuold be “1,2,3…9” .Could anybody help me to explain this? Deeply Grateful.
package main
import (
"fmt"
"sync"
)
func main() {
doOnve()
}
func doOnve() {
var once sync.Once
funBody := func() {
fmt.Println("Only once")
}
c := make(chan int)
for i:=0;i<10;i++{
go func() {
once.Do(funBody)
c <- i
}()
}
for i := 0; i < 10; i++ {
fmt.Println( <- c)
}
}
TL;DR: Always pass data to goroutines through function parameters.
The goroutines in your code are closures that can “see” the variables of the outer function. Usually the loop is finished before the goroutines start printing the value of the loop variable. At that point, the loop variable is already set to the final value.
Passing the values as proper function parameters avoids this situation.
go func(val int) {
once.Do(funBody)
c <- val
}(i) // note the i here