untime.Gosched()用於讓出CPU時間片。這就像跑接力賽,A跑了一會碰到代碼runtime.Gosched()就把接力棒交給B了,A歇着了,B繼續跑。
看代碼:
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") }
輸出結果:
hello
world
hello
注意結果:
1、先輸出了hello,后輸出了world.
2、hello輸出了2個,world輸出了1個(因為第2個hello輸出完,主線程就退出了,第2個world沒機會了)
把代碼中的runtime.Gosched()注釋掉,執行結果是:
hello
hello
因為say("hello")這句占用了時間,等它執行完,線程也結束了,say("world")就沒有機會了。
這里同時可以看出,go中的goroutins並不是同時在運行。事實上,如果沒有在代碼中通過
runtime.GOMAXPROCS(n) 其中n是整數,
指定使用多核的話,goroutins都是在一個線程里的,它們之間通過不停的讓出時間片輪流運行,達到類似同時運行的效果。
還需要學習一句話:
當一個goroutine發生阻塞,Go會自動地把與該goroutine處於同一系統線程的其他goroutines轉移到另一個系統線程上去,以使這些goroutines不阻塞