The goroutine scheduler is not preemptive.

 

go - Why is time.sleep required to run certain goroutines? - Stack Overflow https://stackoverflow.com/questions/15771232/why-is-time-sleep-required-to-run-certain-goroutines

 

package main

import (
//"time"
"fmt"
)

func say(s string) {
for i := 0; i < 5; i++ {
// time.Sleep(100 * time.Microsecond)
fmt.Println(s)
}
}

func main() {
go say("world")
say("hello")
}


hello
hello
hello
hello
hello

 


package main

import (
"time"
"fmt"
)

func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Microsecond)
fmt.Println(s)
}
}

func main() {
go say("world")
say("hello")
}


输出结果不定

hello
world
hello
world
hello
world
world
hello
world
hello


hello
world
hello
world
world
hello
world
hello
hello


world
hello
world
hello
hello
world
hello
world
world
hello

 

posted @ 2018-09-13 15:49  papering  阅读(146)  评论(0编辑  收藏  举报