?
This document uses PHP Chinese website manual Release
import "runtime"
概況
索引
例子
子目錄
Package runtime 包含與 Go 的運行時系統(tǒng)交互的操作,例如控制 goroutines 的函數(shù)。它還包括反映包使用的低級類型信息; 請參閱運行時類型系統(tǒng)的可編程接口的反射文檔。
以下環(huán)境變量($ name 或 %name%,取決于主機操作系統(tǒng))控制 Go 程序的運行時行為。意義和使用可能會從發(fā)布到發(fā)布。
GOGC 變量設置初始垃圾收集目標百分比。當新分配的數(shù)據(jù)與先前收集后剩余的實時數(shù)據(jù)的比率達到此百分比時,會觸發(fā)收集。默認值是 GOGC = 100 。設置 GOGC = off 將完全禁用垃圾回收器。運行時/調(diào)試包的 SetGCPercent 函數(shù)允許在運行時更改此百分比。請參閱https://golang.org/pkg/runtime/debug/#SetGCPercent。
GODEBUG 變量控制運行時內(nèi)的調(diào)試變量。它是一個以逗號分隔的 name = val 對列表,用于設置這些命名變量:
allocfreetrace: setting allocfreetrace=1 causes every allocation to be profiled and a stack trace printed on each object's allocation and free.cgocheck: setting cgocheck=0 disables all checks for packages using cgo to incorrectly pass Go pointers to non-Go code.Setting cgocheck=1 (the default) enables relatively cheap checks that may miss some errors. Setting cgocheck=2 enables expensive checks that should not miss any errors, but will cause your program to run slower.efence: setting efence=1 causes the allocator to run in a mode where each object is allocated on a unique page and addresses are never recycled.gccheckmark: setting gccheckmark=1 enables verification of the garbage collector's concurrent mark phase by performing a second mark pass while the world is stopped. If the second pass finds a reachable object that was not found by concurrent mark, the garbage collector will panic.gcpacertrace: setting gcpacertrace=1 causes the garbage collector to print information about the internal state of the concurrent pacer.gcshrinkstackoff: setting gcshrinkstackoff=1 disables moving goroutines onto smaller stacks. In this mode, a goroutine's stack can only grow.gcrescanstacks: setting gcrescanstacks=1 enables stack re-scanning during the STW mark termination phase. This is helpful for debugging if objects are being prematurely garbage collected.gcstoptheworld: setting gcstoptheworld=1 disables concurrent garbage collection,making every garbage collection a stop-the-world event. Setting gcstoptheworld=2also disables concurrent sweeping after the garbage collection finishes.gctrace: setting gctrace=1 causes the garbage collector to emit a single line to standard error at each collection, summarizing the amount of memory collected and the length of the pause. Setting gctrace=2 emits the same summary but also repeats each collection. The format of this line is subject to change.Currently, it is: gc # @#s #%: #+#+# ms clock, #+#/#/#+# ms cpu, #->#-># MB, # MB goal, # P where the fields are as follows: gc # the GC number, incremented at each GC @#s time in seconds since program start #% percentage of time spent in GC since program start #+...+# wall-clock/CPU times for the phases of the GC #->#-># MB heap size at GC start, at GC end, and live heap # MB goal goal heap size # P number of processors used The phases are stop-the-world (STW) sweep termination, concurrent mark and scan, and STW mark termination. The CPU timesfor mark/scan are broken down in to assist time (GC performed inline with allocation), background GC time, and idle GC time.If the line ends with "(forced)", this GC was forced by a runtime.GC() call.Setting gctrace to any value > 0 also causes the garbage collector to emit a summary when memory is released back to the system.This process of returning memory to the system is called scavenging.The format of this summary is subject to change.Currently it is: scvg#: # MB released printed only if non-zero scvg#: inuse: # idle: # sys: # released: # consumed: # (MB)where the fields are as follows: scvg# the scavenge cycle number, incremented at each scavenge inuse: # MB used or partially used spans idle: # MB spans pending scavenging sys: # MB mapped from the system released: # MB released to the system consumed: # MB allocated from the system memprofilerate: setting memprofilerate=X will update the value of runtime.MemProfileRate.When set to 0 memory profiling is disabled. Refer to the description ofMemProfileRate for the default value.invalidptr: defaults to invalidptr=1, causing the garbage collector and stack copier to crash the program if an invalid pointer value (for example, 1)is found in a pointer-typed location. Setting invalidptr=0 disables this check.This should only be used as a temporary workaround to diagnose buggy code.The real fix is to not store integers in pointer-typed locations.sbrk: setting sbrk=1 replaces the memory allocator and garbage collectorwith a trivial allocator that obtains memory from the operating system and never reclaims any memory.scavenge: scavenge=1 enables debugging mode of heap scavenger.scheddetail: setting schedtrace=X and scheddetail=1 causes the scheduler to emit detailed multiline info every X milliseconds, describing state of the scheduler,processors, threads and goroutines.schedtrace: setting schedtrace=X causes the scheduler to emit a single line to standard error every X milliseconds, summarizing the scheduler state.
net 和 net / http 軟件包也指 GODEBUG 中的調(diào)試變量。有關詳情,請參閱這些軟件包的文檔。
GOMAXPROCS 變量限制可同時執(zhí)行用戶級 Go 代碼的操作系統(tǒng)線程的數(shù)量。代表 Go 代碼的系統(tǒng)調(diào)用中可以阻止的線程數(shù)量沒有限制; 那些不計入 GOMAXPROCS 限制。該軟件包的 GOMAXPROCS 函數(shù)查詢和更改限制。
GOTRACEBACK 變量控制 Go 程序由于未發(fā)現(xiàn)的恐慌或意外的運行時情況而失敗時產(chǎn)生的輸出量。默認情況下,失敗打印當前 goroutine 的堆棧跟蹤,在運行系統(tǒng)內(nèi)部隱藏函數(shù),然后退出,退出代碼2.如果沒有當前的 goroutine 或者失敗是失敗,則打印所有 goroutine 的堆棧跟蹤內(nèi)部的運行時間。GOTRACEBACK = none 完全忽略 goroutine 堆棧軌跡。GOTRACEBACK = single(默認)的行為如上所述。GOTRACEBACK = 全部為所有用戶創(chuàng)建的例程添加堆棧跟蹤。GOTRACEBACK =系統(tǒng)類似于“全部”,但為運行時功能添加堆棧幀并顯示運行時在內(nèi)部創(chuàng)建的 goroutines 。GOTRACEBACK =崩潰與“系統(tǒng)”類似,但是以操作系統(tǒng)特定的方式崩潰而不是退出。例如,在 Unix 系統(tǒng)上,崩潰引發(fā) SIGABRT 以觸發(fā)核心轉(zhuǎn)儲。由于歷史原因,GOTRACEBACK 設置0,1和2分別是 none,all 和 system 的同義詞。運行時/調(diào)試包的 SetTraceback 函數(shù)允許在運行時增加輸出量,但不能減少低于環(huán)境變量指定的量。請參閱https://golang.org/pkg/runtime/debug/#SetTraceback。但它不能減少低于環(huán)境變量指定的數(shù)量。請參閱https://golang.org/pkg/runtime/debug/#SetTraceback。但它不能減少低于環(huán)境變量指定的數(shù)量。請參閱https://golang.org/pkg/runtime/debug/#SetTraceback。
GOARCH,GOOS,GOPATH 和 GOROOT 環(huán)境變量完成 Go 環(huán)境變量的設置。他們影響 Go 程序的構建(請參閱https://golang.org/cmd/go和https://golang.org/pkg/go/build)。GOARCH,GOOS 和 GOROOT 是在編譯時記錄的,并且可以通過這個包中的常量或函數(shù)提供,但它們不會影響運行時系統(tǒng)的執(zhí)行。
常量
變量
func BlockProfile(p []BlockProfileRecord) (n int, ok bool)
func Breakpoint()
func CPUProfile() []byte
func Caller(skip int) (pc uintptr, file string, line int, ok bool)
func Callers(skip int, pc []uintptr) int
func GC()
func GOMAXPROCS(n int) int
func GOROOT() string
func Goexit()
func GoroutineProfile(p []StackRecord) (n int, ok bool)
func Gosched()
func KeepAlive(interface{})
func LockOSThread()
func MemProfile(p []MemProfileRecord, inuseZero bool) (n int, ok bool)
func MutexProfile(p []BlockProfileRecord) (n int, ok bool)
func NumCPU() int
func NumCgoCall() int64
func NumGoroutine() int
func ReadMemStats(m *MemStats)
func ReadTrace() []byte
func SetBlockProfileRate(rate int)
func SetCPUProfileRate(hz int)
func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer)
func SetFinalizer(obj interface{}, finalizer interface{})
func SetMutexProfileFraction(rate int) int
func Stack(buf []byte, all bool) int
func StartTrace() error
func StopTrace()
func ThreadCreateProfile(p []StackRecord) (n int, ok bool)
func UnlockOSThread()
func Version() string
type BlockProfileRecord
type Error
type Frame
type Frames
func CallersFrames(callers []uintptr) *Frames
func (ci *Frames) Next() (frame Frame, more bool)
type Func
func FuncForPC(pc uintptr) *Func
func (f *Func) Entry() uintptr
func (f *Func) FileLine(pc uintptr) (file string, line int)
func (f *Func) Name() string
type MemProfileRecord
func (r *MemProfileRecord) InUseBytes() int64
func (r *MemProfileRecord) InUseObjects() int64
func (r *MemProfileRecord) Stack() []uintptr
type MemStats
type StackRecord
func (r *StackRecord) Stack() []uintptr
type TypeAssertionError
func (e *TypeAssertionError) Error() string
func (*TypeAssertionError) RuntimeError()
框架
alg.go atomic_pointer.go cgo.go cgo_mmap.go cgo_sigaction.go cgocall.go cgocallback.go cgocheck.go chan.go compiler.go complex.go cpuflags_amd64.go cpuprof.go cputicks.go debug.go defs_linux_amd64.go env_posix.go error.go extern.go fastlog2.go fastlog2table.go float.go hash64.go hashmap.go hashmap_fast.go heapdump.go iface.go lfstack.go lfstack_64bit.go lock_futex.go malloc.go mbarrier.go mbitmap.go mcache.go mcentral.go mem_linux.go mfinal.go mfixalloc.go mgc.go mgclarge.go mgcmark.go mgcsweep.go mgcsweepbuf.go mgcwork.go mheap.go mprof.go msan0.go msize.go mstats.go netpoll.go netpoll_epoll.go os_linux.go os_linux_generic.go panic.go plugin.go print.go proc.go profbuf.go proflabel.go race0.go rdebug.go relax_stub.go runtime.go runtime1.go runtime2.go rwmutex.go select.go sema.go signal_amd64x.go signal_linux_amd64.go signal_sighandler.go signal_unix.go sigqueue.go sigtab_linux_generic.go sizeclasses.go slice.go softfloat64.go sqrt.go stack.go string.go stubs.go stubs2.go stubs_asm.go stubs_linux.go symtab.go sys_nonppc64x.go sys_x86.go time.go timestub.go trace.go traceback.go type.go typekind.go unaligned1.go utf8.go vdso_linux_amd64.go write_err.go
編譯器是構建運行二進制文件的編譯器工具鏈的名稱。已知的工具鏈是:
gc Also known as cmd/compile.gccgo The gccgo front end, part of the GCC compiler suite.
const Compiler = "gc"
GOARCH 是正在運行的程序的架構目標:386,amd64,arm,s390x 等等之一。
const GOARCH string = sys.GOARCH
GOOS 是運行程序的操作系統(tǒng)目標:達爾文,freebsd,linux 等等之一。
const GOOS string = sys.GOOS
MemProfileRate 控制內(nèi)存配置文件中記錄和報告的內(nèi)存分配部分。分析器旨在按分配的每個 MemProfileRate 字節(jié)對平均一個分配進行采樣。
要在配置文件中包含每個分配的塊,請將 MemProfileRate 設置為1.要完全關閉分析,請將 MemProfileRate 設置為0。
處理內(nèi)存配置文件的工具假定配置文件速率在程序的整個生命周期內(nèi)保持不變,并等于當前值。程序改變內(nèi)存分析速率應該盡早執(zhí)行一次,盡可能早地執(zhí)行程序(例如,在 main 的開始處)。
var MemProfileRate int = 512 * 1024
func BlockProfile(p []BlockProfileRecord) (n int, ok bool)
BlockProfile 返回 n,即當前阻塞配置文件中的記錄數(shù)。如果 len(p)> = n,則 BlockProfile 將配置文件復制到 p 中并返回 n,true 。如果 len(p)<n,則 BlockProfile 不會更改 p 并返回 n,false 。
大多數(shù)客戶端應該使用 runtime/pprof 包或測試包的 -test.blockprofile 標志,而不是直接調(diào)用 BlockProfile 。
func Breakpoint()
Breakpoint 執(zhí)行斷點陷阱。
func CPUProfile() []byte
CPUProfile 應急。它以前提供對由運行時生成的 pprof 格式配置文件的塊的原始訪問。生成該格式的細節(jié)已更改,因此此功能已被刪除。
已棄用:請使用 runtime / pprof 軟件包或 net / http / pprof 軟件包中的處理程序,或者使用測試軟件包的 -test.cpuprofile 標志。
func Caller(skip int) (pc uintptr, file string, line int, ok bool)
Caller 在調(diào)用的 goroutine 的堆棧上報告關于函數(shù)調(diào)用的文件和行號信息。參數(shù)跳過是要提升的堆棧幀的數(shù)量,其中0表示來電者的來電者。(由于歷史原因,呼叫者和呼叫者之間跳過的含義不同)。返回值報告相應呼叫文件中的程序計數(shù)器,文件名和行號。如果無法恢復信息,則布爾值 ok 為 false 。
func Callers(skip int, pc []uintptr) int
Callers 用函數(shù)調(diào)用的返回程序計數(shù)器在調(diào)用 goroutine 的棧上填充 slice pc 。參數(shù)跳過是在 pc 中記錄之前要跳過的堆棧幀的數(shù)量,其中0表示呼叫者本身的幀,1表示呼叫者的呼叫者。它返回寫入 pc 的條目數(shù)。
要將這些 PC 轉(zhuǎn)換為符號信息,如函數(shù)名稱和行號,請使用 CallersFrames 。CallersFrames 占內(nèi)置函數(shù),并將返回程序計數(shù)器調(diào)整為調(diào)用程序計數(shù)器。不鼓勵使用直接對返回的 PC 片進行迭代,因為在任何返回的 PC 上使用 FuncForPC,因為這些不能計入內(nèi)聯(lián)或返回程序計數(shù)器調(diào)整。
func GC()
GC 運行垃圾收集并阻塞調(diào)用方,直到垃圾收集完成。它也可能會阻止整個程序。
func GOMAXPROCS(n int) int
GOMAXPROCS 設置可以同時執(zhí)行的最大 CPU 數(shù)并返回以前的設置。如果 n <1,它不會改變當前設置。本地機器上的邏輯 CPU 數(shù)量可以通過 NumCPU 查詢。當調(diào)度程序改進時,此調(diào)用將消失。
func GOROOT() string
GOROOT 返回 Go 樹的根。它使用 GOROOT 環(huán)境變量(如果已設置),或者使用 Go 構建期間使用的根。
func Goexit()
Goexit 終止調(diào)用它的 goroutine 。沒有其他 goroutine 受到影響。Goexit 在終止 goroutine 之前運行所有延遲調(diào)用。因為 Goexit 并不恐慌,但是,這些延遲函數(shù)中的任何恢復調(diào)用都將返回 nil 。
在主要的例程中調(diào)用 Goexit 會終止那個沒有 func 主要返回的例程。由于 func main 沒有返回,程序繼續(xù)執(zhí)行其他 goroutines 。如果所有其他 goutoutines 退出,程序崩潰。
func GoroutineProfile(p []StackRecord) (n int, ok bool)
GoroutineProfile 返回 n,即活動協(xié)程堆棧配置文件中的記錄數(shù)。如果 len(p)> = n,則 GoroutineProfile 將配置文件復制到 p 中并返回 n,true 。如果 len(p)<n,則 GoroutineProfile 不會更改 p 并返回 n,false 。
大多數(shù)客戶端應該使用 runtime / pprof 包而不是直接調(diào)用 GoroutineProfile 。
func Gosched()
Gosched 產(chǎn)生處理器,允許其他 goroutine 運行。它不會暫停當前的 goroutine,因此執(zhí)行會自動恢復。go:nosplit
func KeepAlive(interface{})
KeepAlive 將其參數(shù)標記為當前可達。這可以確保在調(diào)用 KeepAlive 的程序點之前,該對象不會被釋放,并且其終結(jié)器不會運行。
顯示需要 KeepAlive 的非常簡化的示例:
type File struct { d int }d, err := syscall.Open("/file/path", syscall.O_RDONLY, 0)// ... do something if err != nil ...p := &Filewjcelcm34cruntime.SetFinalizer(p, func(p *File) { syscall.Close(p.d) })var buf [10]byte n, err := syscall.Read(p.d, buf[:])// Ensure p is not finalized until Read returns.runtime.KeepAlive(p)// No more uses of p after this point.
如果沒有 KeepAlive 調(diào)用,終結(jié)器可能會在 syscall 開始時運行。讀取,在 syscall.Read 進行實際系統(tǒng)調(diào)用之前關閉文件描述符。
func LockOSThread()
LockOSThread 將調(diào)用的 goroutine 連接到當前的操作系統(tǒng)線程。在調(diào)用 goroutine 退出或調(diào)用 UnlockOSThread 之前,它將始終在該線程中執(zhí)行,并且沒有其他 goroutine 可以執(zhí)行。
func MemProfile(p []MemProfileRecord, inuseZero bool) (n int, ok bool)
MemProfile 返回每個分配站點分配和釋放的內(nèi)存配置文件。
MemProfile 返回 n,即當前內(nèi)存配置文件中的記錄數(shù)。如果 len(p)> = n,MemProfile 將配置文件復制到 p 中并返回 n,true 。如果 len(p)<n,則 MemProfile 不會更改 p 并返回 n,false 。
如果 inuseZero 為 true,則配置文件包含分配記錄,其中 r.AllocBytes> 0,但 r.AllocBytes == r.FreeBytes 。這些是分配內(nèi)存的站點,但它已全部釋放回運行時。
返回的配置文件可能最多有兩個垃圾回收周期。這是為了避免將配置文件傾向于分配; 因為分配是實時發(fā)生的,但是釋放會延遲到垃圾收集器執(zhí)行清除之前,配置文件只會占用有可能被垃圾收集器釋放的分配。
大多數(shù)客戶端應該使用 runtime / pprof 包或測試包的 -test.memprofile 標志,而不是直接調(diào)用 MemProfile 。
func MutexProfile(p []BlockProfileRecord) (n int, ok bool)
MutexProfile 返回 n,即當前互斥體配置文件中的記錄數(shù)。如果 len(p)> = n,則 MutexProfile 將配置文件復制到 p 中并返回 n,true 。否則,MutexProfile 不會更改 p,并返回 n,false 。
大多數(shù)客戶端應該使用 runtime / pprof 包而不是直接調(diào)用 MutexProfile 。
func NumCPU() int
NumCPU 返回當前進程可用的邏輯 CPU 數(shù)量。
通過在進程啟動時查詢操作系統(tǒng)來檢查可用的 CPU 集合。未反映進程啟動后對操作系統(tǒng) CPU 分配的更改。
func NumCgoCall() int64
NumCgoCall 返回當前進程所做的 cgo 調(diào)用的數(shù)量。
func NumGoroutine() int
NumGoroutine 返回當前存在的 goroutine 的數(shù)量。
func ReadMemStats(m *MemStats)
ReadMemStats 用內(nèi)存分配器統(tǒng)計信息填充 m 。
返回的內(nèi)存分配程序統(tǒng)計信息在調(diào)用 ReadMemStats 時是最新的。這與堆配置文件形成鮮明對比,堆配置文件是最近完成的垃圾回收周期的快照。
func ReadTrace() []byte
ReadTrace 返回下一塊二進制跟蹤數(shù)據(jù),阻塞直到數(shù)據(jù)可用。如果跟蹤關閉,并且所有數(shù)據(jù)已經(jīng)返回,則 ReadTrace 返回 nil 。調(diào)用者必須在再次調(diào)用 ReadTrace 之前復制返回的數(shù)據(jù)。ReadTrace 必須一次從一個 goroutine 調(diào)用。
func SetBlockProfileRate(rate int)
SetBlockProfileRate 控制阻塞配置文件中報告的 goroutine 阻塞事件的一小部分。分析器旨在對阻塞的每個速率納秒的平均阻塞事件進行采樣。
要在配置文件中包含每個阻塞事件,傳遞率= 1.要完全關閉分析,傳遞率<= 0。
func SetCPUProfileRate(hz int)
SetCPUProfileRate 將 CPU 分析速率設置為每秒 hz 個樣本。如果 hz <= 0,SetCPUProfileRate 關閉分析。如果分析器處于打開狀態(tài),則不必先關閉速率,否則無法更改速率。
大多數(shù)客戶端應該使用 runtime/ pprof 包或測試包的 -test.cpuprofile 標志,而不是直接調(diào)用 SetCPUProfileRate 。
func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer)
SetCgoTraceback 記錄三個 C 函數(shù),用于從 C 代碼收集追溯信息并將該追溯信息轉(zhuǎn)換為符號信息。打印使用 cgo 的程序的堆棧軌跡時使用這些。
追蹤和上下文功能可以從信號處理程序中調(diào)用,因此必須僅使用異步信號安全功能。當程序崩潰時,可能會調(diào)用符號函數(shù),因此必須謹慎使用內(nèi)存。沒有任何功能可以回撥到 Go 中。
上下文函數(shù)將被調(diào)用一個參數(shù),一個指向結(jié)構體的指針:
struct { Context uintptr}
在 C 語法中,這個結(jié)構將會是
struct { uintptr_t Context;};
如果 Context 字段為0,則會調(diào)用上下文函數(shù)來記錄當前的回溯上下文。它應該在上下文字段中記錄關于當前執(zhí)行點的任何信息,以便稍后生成堆棧跟蹤,可能是堆棧指針和 PC 。在這種情況下,上下文函數(shù)將從 C 代碼調(diào)用。
如果上下文字段不是0,那么它是前一次調(diào)用上下文函數(shù)返回的值。這種情況在不再需要上下文時被調(diào)用; 也就是說,Go 代碼返回到其 C 代碼調(diào)用方時。這允許上下文功能釋放任何關聯(lián)的資源。
盡管上下文函數(shù)在被調(diào)用時記錄一個完整的堆棧跟蹤是正確的,并且簡單地將其拷貝到回溯函數(shù)中,但在典型的程序中,上下文函數(shù)將被多次調(diào)用,而不會記錄那個回溯上下文。在對上下文函數(shù)的調(diào)用中記錄完整的堆棧跟蹤可能效率不高。
traceback 函數(shù)將被調(diào)用一個參數(shù),一個指向 struct 的指針:
struct { Context uintptr SigContext uintptr Buf *uintptr Max uintptr}
在 C 語法中,這個結(jié)構將會是
struct { uintptr_t Context; uintptr_t SigContext; uintptr_t* Buf; uintptr_t Max;};
上下文字段將為零以從當前程序執(zhí)行點收集回溯。在這種情況下,回溯函數(shù)將從 C 代碼中調(diào)用。
否則,上下文將成為之前由上下文函數(shù)調(diào)用返回的值?;厮莺瘮?shù)應該從程序執(zhí)行中的保存點中收集一個堆棧跟蹤?;厮莺瘮?shù)可以從記錄上下文的執(zhí)行線程以外的執(zhí)行線程調(diào)用,但只有在上下文已知是有效且不變的情況下?;厮莺瘮?shù)也可以在記錄上下文的同一個線程的調(diào)用堆棧中調(diào)用得更深?;厮莺瘮?shù)可以用相同的上下文值多次調(diào)用; 如果可能的話,第一次調(diào)用特定的上下文值時,緩存結(jié)果通常是適當?shù)摹?/p>
如果從 Unix 系統(tǒng)的信號處理程序調(diào)用回溯函數(shù),則 SigContext 將作為傳遞給信號處理程序的信號上下文參數(shù)(C ucontext_t * 轉(zhuǎn)換為 uintptr_t)。這可能用于在發(fā)生信號的位置開始追蹤。如果追蹤函數(shù)沒有從信號處理程序調(diào)用,則 SigContext 將為零。
Buf 是追蹤信息應該存儲的地方。它應該是 PC 值,例如 Buf0 是調(diào)用者的 PC,Buf1 是該函數(shù)的調(diào)用者的 PC,等等。最大值是要存儲的最大條目數(shù)。該函數(shù)應該存儲一個零來表示堆棧的頂部,或者調(diào)用者位于不同的堆棧上,大概是一個 Go 堆棧。
與 runtime.Callers 不同,返回的 PC 值在傳遞給符號函數(shù)時應返回調(diào)用指令的文件/行。不需要額外的減法或適當?shù)臏p法。
符號函數(shù)將用一個參數(shù)來調(diào)用,一個指向 struct 的指針:
struct { PC uintptr // program counter to fetch information for File *byte // file name (NUL terminated) Lineno uintptr // line number Func *byte // function name (NUL terminated) Entry uintptr // function entry point More uintptr // set non-zero if more info for this PC Data uintptr // unused by runtime, available for function}
在 C 語法中,這個結(jié)構將會是
struct { uintptr_t PC; char* File; uintptr_t Lineno; char* Func; uintptr_t Entry; uintptr_t More; uintptr_t Data;};
PC 字段將是通過調(diào)用回溯函數(shù)返回的值。
第一次為特定回溯調(diào)用函數(shù)時,除 PC 之外的所有字段都將為0.如果可能,函數(shù)應該填寫其他字段,如果信息不可用,則將其設置為 0 / nil 。數(shù)據(jù)字段可用于存儲跨呼叫的任何有用信息。如果此 PC 有更多信息,則 More 字段應設置為非零,否則為零。如果更多設置為非零,該功能將再次用同一臺 PC 調(diào)用,并可能返回不同的信息(這是為了與內(nèi)聯(lián)函數(shù)一起使用)。如果 More 為零,則將使用回溯中的下一個 PC 值調(diào)用該函數(shù)。當回溯完成時,PC 將被設置為零,函數(shù)將再次被調(diào)用; 這可能被用來釋放任何信息。每次調(diào)用都會將結(jié)構集的字段設置為與返回時相同的值,但“More”字段為零時的 PC 字段除外。該函數(shù)不能在調(diào)用之間保留結(jié)構體指針的副本。
當調(diào)用 SetCgoTraceback 時,version 參數(shù)是函數(shù)期望接收的結(jié)構的版本號。目前這一定是零。
符號函數(shù)可能為零,在這種情況下,回溯函數(shù)的結(jié)果將顯示為數(shù)字。如果回溯函數(shù)為零,則不會調(diào)用符號函數(shù)。上下文函數(shù)可能為零,在這種情況下,只有在上下文字段設置為零的情況下才會調(diào)用回溯函數(shù)。如果上下文函數(shù)為零,則從 Go 到 C 到 Go 的調(diào)用不會顯示調(diào)用堆棧 C 部分的回溯。
SetCgoTraceback 應該只被調(diào)用一次,理想情況是從一個 init 函數(shù)中調(diào)用。
func SetFinalizer(obj interface{}, finalizer interface{})
SetFinalizer 將與 obj 關聯(lián)的終結(jié)器設置為提供的終結(jié)器函數(shù)。當垃圾收集器發(fā)現(xiàn)具有關聯(lián)終結(jié)器的不可達塊時,它將清除關聯(lián)并在單獨的 goroutine 中運行終結(jié)器(obj)。這使 obj 再次可達,但現(xiàn)在沒有關聯(lián)的終結(jié)器。假設沒有再次調(diào)用 SetFinalizer,下次垃圾收集器看到 obj 無法訪問時,它將釋放 obj 。
SetFinalizer(obj,nil)清除與 obj 關聯(lián)的任何終結(jié)器。
參數(shù) obj 必須是指向通過調(diào)用 new 分配的對象的指針,通過獲取組合文字的地址,或者通過獲取局部變量的地址。參數(shù)終結(jié)器必須是一個函數(shù),它接受一個可以賦予 obj 類型的參數(shù),并且可以有任意忽略的返回值。如果其中任何一個不成立,SetFinalizer 可能會中止該程序。
終結(jié)器以依賴順序運行:如果 A 在 B 點,兩者都有終結(jié)器,否則無法訪問,只有 A 的終結(jié)器運行; 一旦 A 被釋放,B 的終結(jié)器可以運行。如果循環(huán)結(jié)構包含帶終結(jié)器的塊,則不保證該循環(huán)被垃圾收集,并且終結(jié)器不能保證運行,因為沒有遵從依賴關系的排序。
obj 的終結(jié)器計劃在 obj 變得無法訪問之后的某個任意時間運行。不能保證在程序退出之前終結(jié)器會運行,因此通常它們僅用于在長時間運行的程序期間釋放與對象關聯(lián)的非內(nèi)存資源。例如,當程序放棄 os.File 而不調(diào)用 Close 時,os.File 對象可以使用終結(jié)器來關閉相關的操作系統(tǒng)文件描述符,但依靠終結(jié)器來刷新內(nèi)存中的 I 將是錯誤的 / O 緩沖區(qū),如 bufio.Writer,因為在程序退出時緩沖區(qū)不會被刷新。
如果 * obj 的大小為零字節(jié),則不保證終結(jié)器將運行。
不能保證終結(jié)器將運行初始化程序中為包級別變量分配的對象。這些對象可能是鏈接器分配的,而不是堆分配的。
一旦對象變得無法訪問,終結(jié)器可能會運行。為了正確使用終結(jié)器,程序必須確保該對象可以到達,直到不再需要為止。存儲在全局變量中的對象或者可以通過跟蹤來自全局變量的指針找到的對象都是可訪問的。對于其他對象,將對象傳遞給 KeepAlive 函數(shù)的調(diào)用,以標記函數(shù)中必須可達的最后一個點。
例如,如果 p 指向一個包含文件描述符 d 的結(jié)構,并且 p 有一個關閉該文件描述符的終結(jié)器,并且函數(shù)中最后一次使用 p 是對 syscall.Write(pd,buf,size ),那么只要程序進入 syscall.Write,p 可能無法訪問。終結(jié)器可能會在那一刻運行,關閉 pd,導致 syscall.Write 失敗,因為它正在寫入一個關閉的文件描述符(或者更糟糕的是,由一個不同的 goroutine 打開的完全不同的文件描述符)。為了避免這個問題,在調(diào)用 syscall.Write 之后調(diào)用 runtime.KeepAlive(p)。
一個 goroutine 依次運行一個程序的所有終結(jié)器。如果一個終結(jié)者必須運行很長時間,它應該通過啟動一個新 goroutine 來實現(xiàn)。
func SetMutexProfileFraction(rate int) int
SetMutexProfileFraction 控制互斥量配置文件中報告的互斥量爭用事件的分數(shù)。平均報告1個費率事件。之前的費率將返回。
要完全關閉分析,通過率為0.要只讀取當前的速率,通過率為-1。(對于 n> 1,采樣的細節(jié)可能會改變。)
func Stack(buf []byte, all bool) int
Stack 將調(diào)用goroutine的堆棧跟蹤格式化為 buf,并返回寫入 buf 的字節(jié)數(shù)。如果全部為真,則堆棧格式會將當前 goroutine 的跟蹤之后的所有其他 goroutines 的跟蹤信息堆疊到 buf 中。
func StartTrace() error
StartTrace 支持跟蹤當前進程。在追蹤時,數(shù)據(jù)將通過 ReadTrace 進行緩沖并提供。如果跟蹤已啟用,則 StartTrace 將返回錯誤。大多數(shù)客戶端應該使用 runtime/trace package 或測試包的 -test.trace 標志,而不是直接調(diào)用 StartTrace 。
func StopTrace()
StopTrace 停止跟蹤,如果它以前啟用。在跟蹤的所有讀取完成后,StopTrace 才會返回。
func ThreadCreateProfile(p []StackRecord) (n int, ok bool)
ThreadCreateProfile 返回 n,線程創(chuàng)建配置文件中的記錄數(shù)。如果 len(p)> = n,則 ThreadCreateProfile 將配置文件復制到 p 中并返回 n,true 。如果 len(p)<n,則 ThreadCreateProfile 不會更改 p 并返回 n,false 。
大多數(shù)客戶端應該使用 runtime / pprof 包而不是直接調(diào)用 ThreadCreateProfile 。
func UnlockOSThread()
UnlockOSThread 從其固定的操作系統(tǒng)線程中解除調(diào)用的 goroutine 。如果調(diào)用的 goroutine 沒有調(diào)用 LockOSThread,則 UnlockOSThread 是無操作的。
func Version() string
版本返回 Go 樹的版本字符串。它可以是構建時的提交 hash 和日期,也可以是發(fā)布標簽,如“go1.3”。
BlockProfileRecord 描述了在特定的調(diào)用序列(堆棧跟蹤)發(fā)起的阻塞事件。
type BlockProfileRecord struct { Count int64 Cycles int64 StackRecord}
Error 接口標識運行時錯誤。
type Error interface { error // RuntimeError is a no-op function but // serves to distinguish types that are run time // errors from ordinary errors: a type is a // run time error if it has a RuntimeError method. RuntimeError()}
Frame 是由幀為每個呼叫幀返回的信息。
type Frame struct { // PC is the program counter for the location in this frame. // For a frame that calls another frame, this will be the // program counter of a call instruction. Because of inlining, // multiple frames may have the same PC value, but different // symbolic information. PC uintptr // Func is the Func value of this call frame. This may be nil // for non-Go code or fully inlined functions. Func *Func // Function is the package path-qualified function name of // this call frame. If non-empty, this string uniquely // identifies a single function in the program. // This may be the empty string if not known. // If Func is not nil then Function == Func.Name(). Function string // File and Line are the file name and line number of the // location in this frame. For non-leaf frames, this will be // the location of a call. These may be the empty string and // zero, respectively, if not known. File string Line int // Entry point program counter for the function; may be zero // if not known. If Func is not nil then Entry == // Func.Entry(). Entry uintptr}
幀可以用來獲取由呼叫者返回的 PC 片段的功能/文件/線路信息。
type Frames struct { // contains filtered or unexported fields}
package mainimport ("fmt""runtime""strings")func main() { c := func() {// Ask runtime.Callers for up to 10 pcs, including runtime.Callers itself. pc := make([]uintptr, 10) n := runtime.Callers(0, pc)if n == 0 {// No pcs available. Stop now.// This can happen if the first argument to runtime.Callers is large.return} pc = pc[:n] // pass only valid pcs to runtime.CallersFrames frames := runtime.CallersFrames(pc)// Loop to get frames.// A fixed number of pcs can expand to an indefinite number of Frames.for { frame, more := frames.Next()// To keep this example's output stable// even if there are changes in the testing package,// stop unwinding when we leave package runtime.if !strings.Contains(frame.File, "runtime/") {break} fmt.Printf("- more:%v | %s\n", more, frame.Function)if !more {break}}} b := func() { c() } a := func() { b() }a()}
func CallersFrames(callers []uintptr) *Frames
CallersFrames 獲取由調(diào)用者返回的一部分 PC 值,并準備返回函數(shù)/文件/行信息。在完成幀之前,不要更改切片。
func (ci *Frames) Next() (frame Frame, more bool)
Next 返回下一個調(diào)用者的幀信息。如果 more為false,則不再有主叫方(Frame 值有效)。
Func 表示正在運行的二進制文件中的 Go 函數(shù)。
type Func struct { // contains filtered or unexported fields}
func FuncForPC(pc uintptr) *Func
FuncForPC 返回描述包含給定程序計數(shù)器地址的函數(shù)的 * Func,否則返回 nil 。
如果 pc 由于內(nèi)聯(lián)而代表多個函數(shù),它將返回描述最外層函數(shù)的 * Func 。
func (f *Func) Entry() uintptr
Entry 返回函數(shù)的入口地址。
func (f *Func) FileLine(pc uintptr) (file string, line int)
FileLine 返回與程序計數(shù)器 pc 相對應的源代碼的文件名和行號。如果 pc 不是 f 中的程序計數(shù)器,結(jié)果將不準確。
func (f *Func) Name() string
Name 返回函數(shù)的名稱。
MemProfileRecord 描述了由特定調(diào)用序列(堆棧跟蹤)分配的活動對象。
type MemProfileRecord struct { AllocBytes, FreeBytes int64 // number of bytes allocated, freed AllocObjects, FreeObjects int64 // number of objects allocated, freed Stack0 [32]uintptr // stack trace for this record; ends at first 0 entry}
func (r *MemProfileRecord) InUseBytes() int64
InUseBytes 返回正在使用的字節(jié)數(shù)(AllocBytes - FreeBytes)。
func (r *MemProfileRecord) InUseObjects() int64
InUseObjects 返回正在使用的對象的數(shù)量(AllocObjects - FreeObjects)。
func (r *MemProfileRecord) Stack() []uintptr
Stack 返回與記錄相關的堆棧跟蹤,它是 r.Stack0 的前綴。
MemStats 記錄有關內(nèi)存分配器的統(tǒng)計信息。
type MemStats struct { // Alloc is bytes of allocated heap objects. // // This is the same as HeapAlloc (see below). Alloc uint64 // TotalAlloc is cumulative bytes allocated for heap objects. // // TotalAlloc increases as heap objects are allocated, but // unlike Alloc and HeapAlloc, it does not decrease when // objects are freed. TotalAlloc uint64 // Sys is the total bytes of memory obtained from the OS. // // Sys is the sum of the XSys fields below. Sys measures the // virtual address space reserved by the Go runtime for the // heap, stacks, and other internal data structures. It's // likely that not all of the virtual address space is backed // by physical memory at any given moment, though in general // it all was at some point. Sys uint64 // Lookups is the number of pointer lookups performed by the // runtime. // // This is primarily useful for debugging runtime internals. Lookups uint64 // Mallocs is the cumulative count of heap objects allocated. // The number of live objects is Mallocs - Frees. Mallocs uint64 // Frees is the cumulative count of heap objects freed. Frees uint64 // HeapAlloc is bytes of allocated heap objects. // // "Allocated" heap objects include all reachable objects, as // well as unreachable objects that the garbage collector has // not yet freed. Specifically, HeapAlloc increases as heap // objects are allocated and decreases as the heap is swept // and unreachable objects are freed. Sweeping occurs // incrementally between GC cycles, so these two processes // occur simultaneously, and as a result HeapAlloc tends to // change smoothly (in contrast with the sawtooth that is // typical of stop-the-world garbage collectors). HeapAlloc uint64 // HeapSys is bytes of heap memory obtained from the OS. // // HeapSys measures the amount of virtual address space // reserved for the heap. This includes virtual address space // that has been reserved but not yet used, which consumes no // physical memory, but tends to be small, as well as virtual // address space for which the physical memory has been // returned to the OS after it became unused (see HeapReleased // for a measure of the latter). // // HeapSys estimates the largest size the heap has had. HeapSys uint64 // HeapIdle is bytes in idle (unused) spans. // // Idle spans have no objects in them. These spans could be // (and may already have been) returned to the OS, or they can // be reused for heap allocations, or they can be reused as // stack memory. // // HeapIdle minus HeapReleased estimates the amount of memory // that could be returned to the OS, but is being retained by // the runtime so it can grow the heap without requesting more // memory from the OS. If this difference is significantly // larger than the heap size, it indicates there was a recent // transient spike in live heap size. HeapIdle uint64 // HeapInuse is bytes in in-use spans. // // In-use spans have at least one object in them. These spans // can only be used for other objects of roughly the same // size. // // HeapInuse minus HeapAlloc esimates the amount of memory // that has been dedicated to particular size classes, but is // not currently being used. This is an upper bound on // fragmentation, but in general this memory can be reused // efficiently. HeapInuse uint64 // HeapReleased is bytes of physical memory returned to the OS. // // This counts heap memory from idle spans that was returned // to the OS and has not yet been reacquired for the heap. HeapReleased uint64 // HeapObjects is the number of allocated heap objects. // // Like HeapAlloc, this increases as objects are allocated and // decreases as the heap is swept and unreachable objects are // freed. HeapObjects uint64 // StackInuse is bytes in stack spans. // // In-use stack spans have at least one stack in them. These // spans can only be used for other stacks of the same size. // // There is no StackIdle because unused stack spans are // returned to the heap (and hence counted toward HeapIdle). StackInuse uint64 // StackSys is bytes of stack memory obtained from the OS. // // StackSys is StackInuse, plus any memory obtained directly // from the OS for OS thread stacks (which should be minimal). StackSys uint64 // MSpanInuse is bytes of allocated mspan structures. MSpanInuse uint64 // MSpanSys is bytes of memory obtained from the OS for mspan // structures. MSpanSys uint64 // MCacheInuse is bytes of allocated mcache structures. MCacheInuse uint64 // MCacheSys is bytes of memory obtained from the OS for // mcache structures. MCacheSys uint64 // BuckHashSys is bytes of memory in profiling bucket hash tables. BuckHashSys uint64 // GCSys is bytes of memory in garbage collection metadata. GCSys uint64 // OtherSys is bytes of memory in miscellaneous off-heap // runtime allocations. OtherSys uint64 // NextGC is the target heap size of the next GC cycle. // // The garbage collector's goal is to keep HeapAlloc ≤ NextGC. // At the end of each GC cycle, the target for the next cycle // is computed based on the amount of reachable data and the // value of GOGC. NextGC uint64 // LastGC is the time the last garbage collection finished, as // nanoseconds since 1970 (the UNIX epoch). LastGC uint64 // PauseTotalNs is the cumulative nanoseconds in GC // stop-the-world pauses since the program started. // // During a stop-the-world pause, all goroutines are paused // and only the garbage collector can run. PauseTotalNs uint64 // PauseNs is a circular buffer of recent GC stop-the-world // pause times in nanoseconds. // // The most recent pause is at PauseNs[(NumGC+255)%256]. In // general, PauseNs[N%256] records the time paused in the most // recent N%256th GC cycle. There may be multiple pauses per // GC cycle; this is the sum of all pauses during a cycle. PauseNs [256]uint64 // PauseEnd is a circular buffer of recent GC pause end times, // as nanoseconds since 1970 (the UNIX epoch). // // This buffer is filled the same way as PauseNs. There may be // multiple pauses per GC cycle; this records the end of the // last pause in a cycle. PauseEnd [256]uint64 // NumGC is the number of completed GC cycles. NumGC uint32 // NumForcedGC is the number of GC cycles that were forced by // the application calling the GC function. NumForcedGC uint32 // GCCPUFraction is the fraction of this program's available // CPU time used by the GC since the program started. // // GCCPUFraction is expressed as a number between 0 and 1, // where 0 means GC has consumed none of this program's CPU. A // program's available CPU time is defined as the integral of // GOMAXPROCS since the program started. That is, if // GOMAXPROCS is 2 and a program has been running for 10 // seconds, its "available CPU" is 20 seconds. GCCPUFraction // does not include CPU time used for write barrier activity. // // This is the same as the fraction of CPU reported by // GODEBUG=gctrace=1. GCCPUFraction float64 // EnableGC indicates that GC is enabled. It is always true, // even if GOGC=off. EnableGC bool // DebugGC is currently unused. DebugGC bool // BySize reports per-size class allocation statistics. // // BySize[N] gives statistics for allocations of size S where // BySize[N-1].Size < S ≤ BySize[N].Size. // // This does not report allocations larger than BySize[60].Size. BySize [61]struct { // Size is the maximum byte size of an object in this // size class. Size uint32 // Mallocs is the cumulative count of heap objects // allocated in this size class. The cumulative bytes // of allocation is Size*Mallocs. The number of live // objects in this size class is Mallocs - Frees. Mallocs uint64 // Frees is the cumulative count of heap objects freed // in this size class. Frees uint64 }}
StackRecord 描述了一個執(zhí)行堆棧。
type StackRecord struct { Stack0 [32]uintptr // stack trace for this record; ends at first 0 entry}
func (r *StackRecord) Stack() []uintptr
Stack 返回與記錄相關的堆棧跟蹤,它是 r.Stack0 的前綴。
TypeAssertionError 解釋失敗的類型斷言。
type TypeAssertionError struct { // contains filtered or unexported fields}
func (e *TypeAssertionError) Error() string
func (*TypeAssertionError) RuntimeError()
Name | Synopsis |
---|---|
cgo | Package cgo 包含由 cgo 工具生成的代碼的運行時支持。 |
debug | 程序包調(diào)試包含程序在運行時進行調(diào)試的功能。 |
internal/sys | 包sys包含運行時使用的系統(tǒng)和配置以及特定于體系結(jié)構的常量。 |
pprof | 軟件包 pprof 以 pprof 可視化工具所期望的格式寫入運行時分析數(shù)據(jù)。 |
race | 包比賽實施數(shù)據(jù)競賽檢測邏輯。 |
trace | 執(zhí)行追蹤器。 |