官網文檔對runtime包的介紹:
Package runtime contains operations that interact with Go's runtime system, such as functions to control goroutines. It also includes the low-level type information used by the reflect package; see reflect's documentation for the programmable interface to the run-time type system.
儘管 Go 編譯器產生的是本地可執行代碼,這些代碼仍舊運行在 Go 的 runtime(這部分的代碼可以在 runtime 包中找到)當中。這個 runtime 類似 Java 和 .NET 語言所用到的虛擬機,它負責管理包括內存分配、垃圾回收(第 10.8 節)、棧處理、goroutine、channel、切片(slice)、map 和反射(reflection)等等。
一、常用函數
runtime 調度器是個非常有用的東西,關於 runtime 包幾個方法:
- NumCPU:返回當前系統的 CPU 核數量
- GOMAXPROCS:設置最大的可同時使用的 CPU 核數
通過runtime.GOMAXPROCS函數,應用程序何以在運行期間設置運行時系統中得P最大數量。但這會引起“Stop the World”。所以,應在應用程序最早的調用。並且最好是在運行Go程序之前設置好操作程序的環境變量GOMAXPROCS,而不是在程序中調用runtime.GOMAXPROCS函數。
無論我們傳遞給函數的整數值是什麼值,運行時系統的P最大值總會在1~256之間。
go1.8後,默認讓程序運行在多個核上,可以不用設置了
go1.8前,還是要設置一下,可以更高效的利益cpu
- Gosched:讓當前線程讓出 cpu 以讓其它線程運行,它不會掛起當前線程,因此當前線程未來會繼續執行
這個函數的作用是讓當前 goroutine 讓出 CPU,當一個 goroutine 發生阻塞,Go 會自動地把與該 goroutine 處於同一系統線程的其他 goroutine 轉移到另一個系統線程上去,以使這些 goroutine 不阻塞。 - Goexit:退出當前 goroutine(但是defer語句會照常執行)
- NumGoroutine:返回正在執行和排隊的任務總數
runtime.NumGoroutine函數在被調用後,會返回系統中的處於特定狀態的Goroutine的數量。這裡的特指是指Grunnable\Gruning\Gsyscall\Gwaition。處於這些狀態的Groutine即被看做是活躍的或者說正在被調度。
注意:垃圾回收所在Groutine的狀態也處於這個範圍內的話,也會被納入該計數器。 - GOOS:目標操作系統
- runtime.GC:會讓運行時系統進行一次強制性的垃圾收集
1.強制的垃圾回收:不管怎樣,都要進行的垃圾回收。2.非強制的垃圾回收:只會在一定條件下進行的垃圾回收(即運行時,系統自上次垃圾回收之後新申請的堆內存的單元(也成為單元增量)達到指定的數值)。 - GOROOT:獲取goroot目錄
- GOOS : 查看目標操作系統 很多時候,我們會根據平臺的不同實現不同的操作,就而已用GOOS了:
二、示例代碼:
1.獲取goroot和os:
<code>fmt
.Println
("GOROOT-->"
,runtime.GOROOT())fmt
.Println
("os/platform-->"
,runtime.GOOS) /<code>
2.獲取CPU數量,和設置CPU數量:
<code>func
init
()
{ fmt.Println("邏輯CPU的核數:"
,runtime.NumCPU()) n := runtime.GOMAXPROCS(runtime.NumCPU()) fmt.Println(n) } /<code>
3.Gosched():
<code>func
main
()
{go
func
()
{for
i :=0
; i5
; i++ { fmt.Println("goroutine。。。"
) } }() for
i :=0
; i4
; i++ { runtime.Gosched() fmt.Println("main。。"
) } } /<code>
4.Goexit的使用(終止協程)
<code>func
main
()
{go
func
()
{ fmt.Println("goroutine開始。。。"
) fun() fmt.Println("goroutine結束。。"
) }() time.Sleep(3
*time.Second) } func
fun
()
{defer
fmt.Println("defer。。。"
) runtime.Goexit() fmt.Println("fun函數。。。"
) } /<code>