網上看到個問題:ui
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") }
只有使用time.sleep(100 * time.Millisecond) 時纔會連續打出5個hello world spa
解釋是 go 是非搶佔的,只有出讓cpu時,另一個協程纔會運行。若是沒有time.sleep(100 * time.Millisecond)就只會打出5個hello出來。code
還有另一個協程切換的方式:協程
package main import ( "fmt"
"runtime"
)
func say(s string) { for i := 0; i < 5; i++ {
runtime.Gosched()
fmt.Println(s)blog
} } func main() { go say("world") say("hello") }
這個只是打出了5 個hello 4個world ----緣由不明。string
比對了下 Gosched() 和 Sleep() 二者運行的時候系統的狀況:io
package main import ( // "fmt" "runtime" // "time" ) func say(){ for i := 0; i < 10000000; i++{ // time.Sleep(1 * time.Millisecond) runtime.Gosched() // fmt.Println(s) } } func main(){ go say() say() }
發現cpu使用率在使用Gosched() 時 比 Sleep() 要高,可是運行的時間比Sleep()的方式明顯要短一些。---這裏面切換的方式須要在網上找找有沒有資料了.class
相關:import
http://stackoverflow.com/questions/15771232/why-is-time-sleep-required-to-run-certain-goroutinesrequire