这个函数的作用是让当前goroutine让出CPU,好让其它的goroutine获得执行的机会。
示例一
func test1() {
go say("world")
say("hello")
}
func say(s string) {
runtime.GOMAXPROCS(1)
for i := 0 ; i < 2; i++ {
runtime.Gosched()
fmt.Println(s)
}
}
运行结果:
hello
world
hello
如果将runtime.GOMAXPROCS(1)去掉可能会出现
hello
world
world
hello
如果将runtime.Gosched()去掉可能会出现
hello
hello
示例二
func test2() {
names := []string{"Lily","yoyo","cersei","rose","annei"}
for _,name := range names{
go func() {
fmt.Println(name)
}()
}
runtime.GOMAXPROCS(1)
runtime.Gosched()
}
运行结果:
annei
annei
annei
annei
annei
872



被折叠的 条评论
为什么被折叠?



