From the go routine example here: https://gobyexample.com/goroutines, why doesn't replacing the fmt.Scanln
code with a time.sleep(2)
work?
If you replace the last three lines with time.Sleep(2)
, the go routines don't print anything.
func main() {
f("direct")
go f("goroutine")
go func(msg string) {
fmt.Println(msg)
}("going")
time.Sleep(2)
}
time.Sleep
takes time.Duration
as an argument, which is in nanoseconds. If you want seconds, use time.Sleep(2*time.Second)
:
f("direct")
go f("goroutine")
go func(msg string) {
fmt.Println(msg)
}("going")
time.Sleep(2 * time.Second)
Playground: http://play.golang.org/p/lgKSyAW4RO.
But it's always better to use channels or tools from package sync
for synchronisation.