go runtime.Gosched() 和 time.Sleep() 作协程切换

   网上看到个问题: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