go runtime包
阿新 • • 發佈:2021-11-10
-
Gosched:讓當前協程讓出cpu以讓其他協程執行,它不會掛起當前協程,因此當前協程未來會繼續執行
-
NumCPU:返回當前系統的CPU核數量
-
GOMAXPROCS:設定最大的可同時使用的CPU核數
-
Goexit:退出當前goroutine(但是defer語句會照常執行)
-
NumGoroutine:返回真該執行和排隊的任務總數
-
GOOS:目標作業系統
- GOROOT:返回本機的GO路徑
1. runtime.Gosched() 讓出當前cpu 時間片
import ( "fmt" "runtime" ) func main() { go func(sstring) { for i := 0; i < 2; i++ { fmt.Println(s) } }("world") for i := 0; i < 2; i++ { // 用於讓出CPU時間片,讓出當前goroutine的執行許可權,排程器安排其它等待的任務執行, runtime.Gosched() fmt.Println("hello") } }
2.runtime.Goexit() 退出當前協程
package main import ( "fmt" "runtime" "time" ) func test1() { defer fmt.Println("cc") //return //終止此函式 runtime.Goexit() //終止所在的協程 fmt.Println("ddd") } func main() { //建立新建的協程 go func() { fmt.Println("aaaaaa") //呼叫了別的函式 test1() fmt.Println("bbbbb") }() //防止主協程執行完畢 time.Sleep(100*time.Second) }