package main
import (
"fmt"
"time"
)
func main() {
var x int
go func() {
for {
x++
}
}()
time.Sleep(time.Second)
fmt.Println("x =", x) // x = 0, why?
}
thanks
package main
import (
"fmt"
"time"
)
func main() {
var x int
go func() {
for {
x++
}
}()
time.Sleep(time.Second)
fmt.Println("x =", x) // x = 0, why?
}
thanks
Because your goroutine never had the opportunity to run. main
exits before the scheduler schedules it. You need some sort of synchronization like a channel or sync.WaitGroup
Shouldn’t time.Sleep()
give other go routines the opportunity to run?
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.