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时的根目录。

扫描二维码关注公众号,回复: 5361739 查看本文章

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 }

 未完待续

猜你喜欢

转载自www.cnblogs.com/wanghui-garcia/p/10331590.html