Golang程式許可權排程包runtime三大函式Gosched、Goexit、GOMAXPROCS

OldBoy~發表於2018-09-16

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。最好在主函式在開始前設定它,因為設定它會停止當前程式的執行。

GO預設是使用一個CPU核的,除非設定runtime.GOMAXPROCS
那麼在多核環境下,什麼情況下設定runtime.GOMAXPROCS會比較好的提高速度呢?

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

 

 

Gosched()程式碼案例

①:沒有使用Gosched函式

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)
    }
}

 

相關文章