go標准庫的學習-runtime


參考:https://studygolang.com/pkgdoc

導入方式:

import "runtime"

runtime包提供和go運行時環境的互操作,如控制go程的函數。它也包括用於reflect包的低層次類型信息;參見reflect報的文檔獲取運行時類型系統的可編程接口。

 

1.constant常量

const GOOS string = theGoos

GOOS是可執行程序的目標操作系統(將要在該操作系統的機器上執行):darwin、freebsd、linux等。

可以用來判斷你的電腦的系統是什么,然后根據不同的系統實現不同的操作,比如你想要根據系統的不同來說明退出程序使用的不同的快捷鍵,就說可以使用該常量來判斷:

package main 
import(
    "fmt"
    "runtime"
)
var prompt = "Enter a radius and an angle (in degrees), e.g., 12.5 90, " +
    "or %s to quit."
func init(){
    if runtime.GOOS == "window" {
        prompt = fmt.Sprintf(prompt, "Ctrl+Z, Enter")
    }else {
        prompt = fmt.Sprintf(prompt, "Ctrl+D")
    }
}
func main() {
    fmt.Println(prompt)

}

因為我的系統是Unix,所以返回:

userdeMBP:go-learning user$ go run test.go
Enter a radius and an angle (in degrees), e.g., 12.5 90, or Ctrl+D to quit.

 

2.

func GOROOT

func GOROOT() string

GOROOT返回Go的根目錄。如果存在GOROOT環境變量,返回該變量的值;否則,返回創建Go時的根目錄。

func Version

func Version() string

返回Go的版本字符串。它要么是遞交的hash和創建時的日期;要么是發行標簽如"go1.3"。

func GC

func GC()

GC執行一次垃圾回收。

舉例,說明sync.Pool緩存的期限只是兩次gc之間這段時間。使用了runtime.GC(),緩存會被清空,那么結果就會變成:

package main 
import(
    "fmt"
    "sync"
    "runtime"
)

func main() {
    //創建一個對象,如果pool為空,就調用該New;如果沒有定義New,則返回nil
    pipe := &sync.Pool{
        New: func() interface{} {
            return "hello ,New"
        },
    }
    fmt.Println(pipe.Get())//hello ,New
    pipe.Put("hello, put")
    runtime.GC() //作用是GC執行一次垃圾回收
    fmt.Println(pipe.Get())//hello ,New,本來應該是hello, put
}

 

runtime包中幾個用於處理goroutine的函數:

func Goexit

func Goexit()

Goexit終止調用它的go程。其它go程不會受影響。Goexit會在終止該go程前執行所有defer的函數。

在程序的main go程調用本函數,會終結該go程,而不會讓main返回。因為main函數沒有返回,程序會繼續執行其它的go程。如果所有其它go程都退出了,程序就會崩潰。

func Gosched

func Gosched()

Gosched使當前go程放棄處理器,以讓其它go程運行。它不會掛起當前go程,因此當前go程未來會恢復執行。

其實就是讓該goroutine讓CPU把時間片讓給別的goroutine,下次某個時候再繼續執行,舉例:

package main 
import(
    "fmt"
    "runtime"
)
func say(s string) {
    for i := 0; i < 3; i++{
        runtime.Gosched()
        fmt.Println(s)
    }
}

func main() {
    go say("world")
    say("hello")
}

返回:

userdeMacBook-Pro:go-learning user$ go run test.go
world
hello
world
hello
world
hello

func NumGoroutine

func NumGoroutine() int

NumGoroutine返回當前存在的Go程數。

func NumCPU

func NumCPU() int

NumCPU返回本地機器的邏輯CPU個數。

func GOMAXPROCS

func GOMAXPROCS(n int) int

GOMAXPROCS設置可同時執行的最大CPU數,並返回先前的設置。 若 n < 1,它就不會更改當前設置。本地機器的邏輯CPU數可通過 NumCPU 查詢。本函數在調度程序優化后會去掉。設置了同時運行邏輯代碼的

package main 
import(
    "fmt" "runtime" ) func main() { fmt.Println(runtime.GOROOT()) // /usr/local/Cellar/go/1.11.4/libexec fmt.Println(runtime.Version()) //go1.11.4 fmt.Println(runtime.NumCPU()) //8 fmt.Println(runtime.GOMAXPROCS(runtime.NumCPU())) //8 }

 未完待續

 


免責聲明!

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



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