In the GO tutorial, we have this slide: Goroutines
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
}
Running this code produces expected results ("world" and "hello" written to the screen interchangeably 5 times).
However, if we comment out time.Sleep
(and consequently, the "time"
line of the import) and run the program again, we are left with only "hello" written to the screen five times.
What is so important about time.Sleep
that saves the goroutine from dying?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…