Skip to content

Instantly share code, notes, and snippets.

@pylemon
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pylemon/73171f6659e2e3eb2351 to your computer and use it in GitHub Desktop.
Save pylemon/73171f6659e2e3eb2351 to your computer and use it in GitHub Desktop.
demo for gosched and gorouting
package main
import (
"fmt"
"runtime"
)
func say(s string) {
for i := 0; i < 2; i++ {
runtime.Gosched()
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
}
// go say("world") 启动一个 gorouting
// say("hello") Gosched
// go say("world") Gosched
// say("hello") 继续 打印了 hello
// say("hello") Gosched
// go say("world") 继续 打印了 world
// go say("world") Gosched
// 这时有2种可能,
// say("hello") 继续 打印了 hello
// 或者
// go say("world") 继续 打印了 world
// go say("world") Gosched
// 然后
// say("hello") 调用完成,返回main()函数,main()函数返回程序结束,
// 程序结束时不会等待其他 gorouting 结束,因此 go say("world") 的第二次还没来得及输出。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment