Golang進程權限調度包runtime三大函數Gosched、Goexit、GOMAXPROCS

轉自:http://www.javashuo.com/article/p-zzebglyf-cx.htmlhtml


 

runtime.Gosched(),用於讓出CPU時間片,讓出當前goroutine的執行權限,調度器安排其它等待的任務運行,並在下次某個時候從該位置恢復執行。這就像跑接力賽,A跑了一會碰到代碼runtime.Gosched()就把接力棒交給B了,A歇着了,B繼續跑。併發


runtime.Goexit(),調用此函數會當即使當前的goroutine的運行終止(終止協程),而其它的goroutine並不會受此影響。runtime.Goexit在終止當前goroutine前會先執行此goroutine的還未執行的defer語句。請注意千萬別在主函數調用runtime.Goexit,由於會引起panic。函數


runtime.GOMAXPROCS(),用來設置能夠並行計算的CPU核數最大值,並返回以前的值。性能

默認此函數的值與CPU邏輯個數相同,即有多少個goroutine併發執行,固然能夠設置它,它的取值是1~256。最好在主函數在開始前設置它,由於設置它會中止當前程序的運行。spa

GO默認是使用一個CPU核的,除非設置runtime.GOMAXPROCS
那麼在多核環境下,什麼狀況下設置runtime.GOMAXPROCS會比較好的提升速度呢?code

適合於CPU密集型、並行度比較高的情景。若是是IO密集型,CPU之間的切換也會帶來性能的損失。協程

 

 

Gosched()代碼案例htm

①:沒有使用Gosched函數blog

複製代碼
package main
import (
    "fmt"
)

func main() {

    go func() { //子協程   //沒來的及執行主進程結束
        for i := 0; i < 5; i++ {
            fmt.Println("go")
        }
    }()

    for i := 0; i < 2; i++ { //默認先執行主進程主進程執行完畢
        fmt.Println("hello")
    }
}
複製代碼
hello
hello

②:使用Gosched函數進程

複製代碼
package main
import (
    "fmt"
    "runtime"
)

func main() {
    go func() {  //讓子協程先執行
        for i := 0; i < 5; i++ {
            fmt.Println("go")
        }
    }()

    for i := 0; i < 2; i++ {
        //讓出時間片,先讓別的協議執行,它執行完,再回來執行此協程
        runtime.Gosched()
        fmt.Println("hello")
    }
}
複製代碼
複製代碼
go
go
go
go
go
hello
hello
複製代碼

 Goexit()代碼案例

複製代碼
package main

import (
    "fmt"
    "runtime"
)

func test() {
    defer fmt.Println("ccccccccccccc")

    //return //終止此函數
    runtime.Goexit() //終止所在的協程

    fmt.Println("dddddddddddddddddddddd")
}

func main() {

    //建立新建的協程
    go func() {
        fmt.Println("aaaaaaaaaaaaaaaaaa")

        //調用了別的函數
        test()

        fmt.Println("bbbbbbbbbbbbbbbbbbb")
    }() //別忘了()

    //特意寫一個死循環,目的不讓主協程結束
    for {
    }
}
複製代碼
aaaaaaaaaaaaaaaaaa
ccccccccccccc

GOMAXPROCS()代碼案例

複製代碼
package main

import (
    "fmt"
    "runtime"
)

func main() {
    //n := runtime.GOMAXPROCS(1) //指定以1核運算
    n := runtime.GOMAXPROCS(4) //指定以4核運算
    fmt.Println("n = ", n)

    for {
        go fmt.Print(1)
        fmt.Print(0)
    }
}
複製代碼
相關文章
相關標籤/搜索