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


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM