Package runtime

Overview ▾

包运行时包含与Go的运行时系统交互的操作,例如控制goroutine的函数. 它还包括反射包使用的低级类型信息. 有关运行时类型系统的可编程接口,请参见反射的文档.

Environment Variables

以下环境变量($ name或%name%,取决于主机操作系统)控制Go程序的运行时行为. 发行版之间的含义和使用可能会有所不同.

GOGC变量设置初始垃圾回收目标百分比. 当新分配的数据与上一个收集之后剩余的实时数据之比达到此百分比时,将触发收集. 默认值为GOGC = 100. 设置GOGC = off将完全禁用垃圾收集器. 运行时/调试包的SetGCPercent函数允许在运行时更改此百分比. 请参阅https://golang.org/pkg/runtime/debug/#SetGCPercent .

GODEBUG变量控制运行时中的调试变量. 这是一个用逗号分隔的name = val对列表,用于设置以下命名变量:

allocfreetrace: setting allocfreetrace=1 causes every allocation to be
profiled and a stack trace printed on each object's allocation and free.

clobberfree: setting clobberfree=1 causes the garbage collector to
clobber the memory content of an object with bad content when it frees
the object.

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.

gcstoptheworld: setting gcstoptheworld=1 disables concurrent garbage collection,
making every garbage collection a stop-the-world event. Setting gcstoptheworld=2
also 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. 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 times
for mark/scan are broken down in to assist time (GC performed in
line 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

madvdontneed: setting madvdontneed=1 will use MADV_DONTNEED
instead of MADV_FREE on Linux when returning memory to the
kernel. This is less efficient, but causes RSS numbers to drop
more quickly.

memprofilerate: setting memprofilerate=X will update the value of runtime.MemProfileRate.
When set to 0 memory profiling is disabled.  Refer to the description of
MemProfileRate 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 collector
with 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.

tracebackancestors: setting tracebackancestors=N extends tracebacks with the stacks at
which goroutines were created, where N limits the number of ancestor goroutines to
report. This also extends the information returned by runtime.Stack. Ancestor's goroutine
IDs will refer to the ID of the goroutine at the time of creation; it's possible for this
ID to be reused for another goroutine. Setting N to 0 will report no ancestry information.

net,net / http和crypto / tls软件包还引用了GODEBUG中的调试变量. 有关详细信息,请参阅这些软件包的文档.

GOMAXPROCS变量限制了可以同时执行用户级Go代码的操作系统线程的数量. 对代表Go代码的系统调用中可以阻止的线程数量没有限制; 那些不计入GOMAXPROCS限制. 该软件包的GOMAXPROCS函数查询并更改限制.

GORACE变量为使用-race构建的程序配置了竞争检测器. 有关详细信息,请参见https://golang.org/doc/articles/race_detector.html .

GOTRACEBACK变量控制在Go程序由于未恢复的紧急情况或意外的运行时条件而失败时生成的输出量. 默认情况下,故障将打印当前goroutine的堆栈跟踪,清除运行时系统内部的函数,然后以退出代码2退出.如果没有当前goroutine或故障是失败,则故障将打印所有goroutine的堆栈跟踪.运行时内部的. GOTRACEBACK = none完全省略goroutine堆栈跟踪. GOTRACEBACK = single(默认)的行为如上所述. GOTRACEBACK = all为所有用户创建的goroutine添加堆栈跟踪. GOTRACEBACK = system类似于" all",但为运行时功能添加了堆栈框架,并显示了运行时在内部创建的goroutine. GOTRACEBACK = crash类似于" system",但是以特定于操作系统的方式崩溃而不是退出. 例如,在Unix系统上,崩溃导致SIGABRT触发核心转储. 由于历史原因,GOTRACEBACK设置0、1和2分别是none,all和system的同义词. 运行时/调试包的SetTraceback函数允许在运行时增加输出量,但不能将其减少到环境变量指定的量以下. 请参阅https://golang.org/pkg/runtime/debug/#SetTraceback .

GOARCH,GOOS,GOPATH和GOROOT环境变量完善了Go环境变量集. 它们会影响Go程序的构建(请参阅https://golang.org/cmd/gohttps://golang.org/pkg/go/build ). GOARCH,GOOS和GOROOT会在编译时记录下来,并可以通过此包中的常量或函数来使用,但它们不会影响运行时系统的执行.

Index ▾

Constants
Variables
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(x 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()

Examples

Frames

Package files

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.go cpuflags_amd64.go cpuprof.go cputicks.go debug.go debugcall.go debuglog.go debuglog_off.go defs_linux_amd64.go env_posix.go error.go extern.go fastlog2.go fastlog2table.go float.go hash64.go heapdump.go iface.go lfstack.go lfstack_64bit.go lock_futex.go malloc.go map.go map_fast32.go map_fast64.go map_faststr.go mbarrier.go mbitmap.go mcache.go mcentral.go mem_linux.go mfinal.go mfixalloc.go mgc.go mgclarge.go mgcmark.go mgcscavenge.go mgcstack.go mgcsweep.go mgcsweepbuf.go mgcwork.go mheap.go mprof.go msan0.go msize.go mstats.go mwbbuf.go netpoll.go netpoll_epoll.go os_linux.go os_linux_generic.go os_linux_noauxv.go os_nonopenbsd.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 sigqueue_note.go sigtab_linux_generic.go sizeclasses.go slice.go softfloat64.go stack.go string.go stubs.go stubs2.go stubs3.go stubs_amd64x.go stubs_linux.go symtab.go sys_nonppc64x.go sys_x86.go time.go timestub.go timestub2.go trace.go traceback.go type.go typekind.go utf8.go vdso_elf64.go vdso_linux.go vdso_linux_amd64.go write_err.go

Constants

编译器是构建正在运行的二进制文件的编译器工具链的名称. 已知的工具链为:

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是运行程序的操作系统目标:darwin,freebsd,linux等之一. 要查看GOOS和GOARCH的可能组合,请运行" go tool dist list".

const GOOS string = sys.GOOS

Variables

MemProfileRate控制在内存配置文件中记录和报告的内存分配比例. 探查器旨在对分配的每个MemProfileRate字节平均抽样一次分配.

要在配置文件中包括每个分配的块,请将MemProfileRate设置为1.要完全关闭分析,请将MemProfileRate设置为0.

处理内存配置文件的工具假定配置文件速率在程序的整个生命周期中都是恒定的,并且等于当前值. 更改内存配置率的程序应该只执行一次,并应尽早在程序执行过程中(例如,在main的开头).

var MemProfileRate int = 512 * 1024

func BlockProfile 1.1

func BlockProfile(p []BlockProfileRecord) (n int, ok bool)

BlockProfile返回n,即当前阻止配置文件中的记录数. 如果len(p)> = n,则BlockProfile将配置文件复制到p中,并返回n,true. 如果len(p)<n,则BlockProfile不会更改p并返回n,否则为false.

大多数客户端应该使用runtime / pprof包或测试包的-test.blockprofile标志,而不是直接调用BlockProfile.

func Breakpoint

func Breakpoint()

断点执行断点陷阱.

func CPUProfile

func CPUProfile() []byte

CPUProfile恐慌. 以前,它提供对运行时生成的pprof格式配置文件的块的原始访问. 生成该格式的详细信息已更改,因此已删除此功能.

不建议使用:使用runtime / pprof程序包,或net / http / pprof程序包中的处理程序,或使用测试程序包的-test.cpuprofile标志.

func Caller

func Caller(skip int) (pc uintptr, file string, line int, ok bool)

调用方报告有关调用goroutine堆栈上的函数调用的文件和行号信息. 参数skip是要提升的堆栈帧数,其中0标识Caller的调用方. (由于历史原因,在Caller和Callers之间,跳过的含义有所不同.)返回值报告相应调用文件中的程序计数器,文件名和行号. 如果不可能恢复该信息,则ok布尔值为False.

func Callers

func Callers(skip int, pc []uintptr) int

调用者使用调用goroutine堆栈上的函数调用的返回程序计数器填充slice pc. 参数skip是在pc中记录之前要跳过的堆栈帧数,其中0表示呼叫者本身的帧,而1表示呼叫者的呼叫者. 它返回写入pc的条目数.

要将这些PC转换为符号信息,例如函数名称和行号,请​​使用CallersFrames. CallersFrames考虑内联函数,并将返回程序计数器调整为调用程序计数器. 不建议直接在返回的PC片上进行迭代,就像在任何返回的PC上使用FuncForPC一样,因为它们不能解释内联或返回程序计数器的调整. 前往:noinline

func GC

func GC()

GC运行垃圾回收并阻塞调用方,直到垃圾回收完成. 它还可能会阻塞整个程序.

func GOMAXPROCS

func GOMAXPROCS(n int) int

GOMAXPROCS设置可以同时执行的最大CPU数,并返回以前的设置. 如果n <1,则不会更改当前设置. 可以使用NumCPU查询本地计算机上的逻辑CPU数量. 调度程序改进后,此呼叫将消失.

func GOROOT

func GOROOT() string

GOROOT返回Go树的根. 它使用GOROOT环境变量(如果在流程开始时设置),或者使用Go构建过程中使用的根目录.

func Goexit

func Goexit()

Goexit终止调用它的goroutine. 没有其他goroutine受到影响. Goexit在终止goroutine之前运行所有延迟的调用. 由于Goexit并非紧急情况,因此这些延迟函数中的任何恢复调用都将返回nil.

从主goroutine调用Goexit会终止该goroutine,而不会返回func main. 由于func main尚未返回,因此程序将继续执行其他goroutine. 如果所有其他goroutine退出,程序将崩溃.

func GoroutineProfile

func GoroutineProfile(p []StackRecord) (n int, ok bool)

GoroutineProfile返回n,即活动goroutine堆栈配置文件中的记录数. 如果len(p)> = n,则GoroutineProfile将配置文件复制到p中并返回n,为true. 如果len(p)<n,则GoroutineProfile不会更改p并返回n,false.

大多数客户端应该使用runtime / pprof软件包,而不是直接调用GoroutineProfile.

func Gosched

func Gosched()

Gosched产生处理器,从而允许其他goroutine运行. 它不会挂起当前的goroutine,因此执行会自动恢复.

func KeepAlive 1.7

func KeepAlive(x interface{})

KeepAlive将其参数标记为当前可达. 这样可以确保在程序中调用KeepAlive的点之前,不释放对象,并且不运行其终结器.

一个非常简化的示例,显示了需要KeepAlive的位置:

type File struct { d int }
d, err := syscall.Open("/file/path", syscall.O_RDONLY, 0)
// ... do something if err != nil ...
p := &File{d}
runtime.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调用,则终结器可以在syscall.Read开始时运行,在syscall.Read进行实际的系统调用之前关闭文件描述符.

func LockOSThread

func LockOSThread()

LockOSThread wires the calling goroutine to its current operating system thread. The calling goroutine will always execute in that thread, and no other goroutine will execute in it, until the calling goroutine has made as many calls to UnlockOSThread as to LockOSThread. If the calling goroutine exits without unlocking the thread, the thread will be terminated.

所有初始化函数都在启动线程上运行. 从init函数调用LockOSThread将导致在该线程上调用main函数.

在调用依赖于每个线程状态的OS服务或非Go库函数之前,goroutine应该先调用LockOSThread.

func MemProfile

func MemProfile(p []MemProfileRecord, inuseZero bool) (n int, ok bool)

MemProfile返回每个分配站点分配和释放的内存的配置文件.

MemProfile返回n,即当前内存配置文件中的记录数. 如果len(p)> = n,则MemProfile将配置文件复制到p中并返回n,true. 如果len(p)<n,则MemProfile不会更改p并返回n,否则为false.

如果inuseZero为true,则配置文件将包括分配记录,其中r.AllocBytes> 0,但r.AllocBytes == r.FreeBytes. 这些是分配了内存的站点,但所有站点都已释放回运行时.

返回的配置文件最多可能有两个旧的垃圾回收周期. 这是为了避免使配置文件偏向分配; 因为分配是实时发生的,但是释放会延迟到垃圾收集器执行清除操作为止,所以概要文件仅考虑了有机会被垃圾收集器释放的分配.

大多数客户端应该使用runtime / pprof包或测试包的-test.memprofile标志,而不是直接调用MemProfile.

func MutexProfile 1.8

func MutexProfile(p []BlockProfileRecord) (n int, ok bool)

MutexProfile返回n,即当前互斥配置文件中的记录数. 如果len(p)> = n,则MutexProfile将配置文件复制到p中并返回n,为true. 否则,MutexProfile不会更改p,并返回n,false.

大多数客户端应该使用runtime / pprof软件包,而不是直接调用MutexProfile.

func NumCPU

func NumCPU() int

NumCPU返回当前进程可用的逻辑CPU数量.

通过在进程启动时查询操作系统来检查可用CPU的集合. 进程启动后不会反映对操作系统CPU分配的更改.

func NumCgoCall

func NumCgoCall() int64

NumCgoCall返回当前进程进行的cgo调用次数.

func NumGoroutine

func NumGoroutine() int

NumGoroutine返回当前存在的goroutine的数量.

func ReadMemStats

func ReadMemStats(m *MemStats)

ReadMemStats使用内存分配器统计信息填充m.

自调用ReadMemStats以来,返回的内存分配器统计信息是最新的. 这与堆概要相反,后者是最新完成的垃圾收集周期的快照.

func ReadTrace 1.5

func ReadTrace() []byte

ReadTrace返回二进制跟踪数据的下一个块,阻塞直到数据可用. 如果关闭了跟踪,并且返回了在跟踪时累积的所有数据,则ReadTrace返回nil. 在再次调用ReadTrace之前,调用者必须复制返回的数据. 必须一次从一个例程中调用ReadTrace.

func SetBlockProfileRate 1.1

func SetBlockProfileRate(rate int)

SetBlockProfileRate控制在阻止配置文件中报告的goroutine阻止事件的比例. 探查器的目标是平均每阻塞1纳秒的速率采样一次阻塞事件.

要将每个阻止事件包括在配置文件中,合格率=1.要完全关闭分析,合格率<= 0.

func SetCPUProfileRate

func SetCPUProfileRate(hz int)

SetCPUProfileRate将CPU分析速率设置为每秒hz个样本. 如果hz <= 0,则SetCPUProfileRate关闭分析. 如果分析器已打开,则必须先将其关闭,然后才能更改速率.

大多数客户端应该使用运行时/ pprof程序包或测试程序包的-test.cpuprofile标志,而不是直接调用SetCPUProfileRate.

func SetCgoTraceback 1.7

func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer)

SetCgoTraceback记录了三个C函数,这些函数用于从C代码中收集回溯信息并将该回溯信息转换为符号信息. 当为使用cgo的程序打印堆栈跟踪时使用这些.

追溯和上下文函数可以从信号处理程序中调用,因此必须仅使用异步信号安全函数. 程序崩溃时可能会调用符号程序功能,因此在使用内存时必须谨慎. 所有功能都不能回调到Go中.

上下文函数将使用单个参数(指向结构的指针)进行调用:

struct {
	Context uintptr
}

用C语法,该结构将是

struct {
	uintptr_t Context;
};

If the Context field is 0, the context function is being called to record the current traceback context. It should record in the Context field whatever information is needed about the current point of execution to later produce a stack trace, probably the stack pointer and PC. In this case the context function will be called from C code.

如果"上下文"字段不为0,则它​​是先前调用上下文函数返回的值. 当不再需要上下文时,称为这种情况; 也就是说,当Go代码返回其C代码调用者时. 这允许上下文功能释放任何关联的资源.

尽管上下文函数在每次调用时都记录完整的堆栈跟踪,并简单地将其复制到traceback函数中是正确的,但是在典型的程序中,上下文函数将被调用很多次,而无需记录该回调上下文. 在对上下文函数的调用中记录完整的堆栈跟踪可能效率很低.

traceback函数将使用单个参数(指向结构的指针)进行调用:

struct {
	Context    uintptr
	SigContext uintptr
	Buf        *uintptr
	Max        uintptr
}

用C语法,该结构将是

struct {
	uintptr_t  Context;
	uintptr_t  SigContext;
	uintptr_t* Buf;
	uintptr_t  Max;
};

上下文字段将为零,以收集从当前程序执行点开始的追溯. 在这种情况下,将从C代码调用回溯函数.

否则,上下文将是先前通过调用上下文函数返回的值. 追溯功能应从程序执行中该保存点收集堆栈跟踪. 可以从执行线程(而不是记录上下文的线程)中调用回溯函数,但是仅当已知上下文有效且不变时才调用该函数. 还可以在记录上下文的同一线程的调用堆栈中更深层次地调用traceback函数. 可以使用相同的Context值多次调用回溯函数. 通常,如果可能的话,第一次为特定的上下文值调用时,将结果缓存是合适的.

如果从Unix系统上的信号处理程序调用traceback函数,则SigContext将是传递给信号处理程序的信号上下文参数(将C ucontext_t *强制转换为uintptr_t). 这可用于在发生信号的点开始跟踪. 如果未从信号处理程序中调用回溯功能,则SigContext将为零.

Buf is where the traceback information should be stored. It should be PC values, such that Buf[0] is the PC of the caller, Buf[1] is the PC of that function's caller, and so on. Max is the maximum number of entries to store. The function should store a zero to indicate the top of the stack, or that the caller is on a different stack, presumably a Go stack.

与runtime.Callers不同,返回的PC值在传递给符号器函数时应返回调用指令的文件/行. 不需要额外的减法或适当的减法.

在所有平台上,当从Go到C到Go的调用请求堆栈跟踪时,都会调用traceback函数. 在linux / amd64,linux / ppc64le和freebsd / amd64上,当正在执行cgo调用的线程接收到信号时,也会调用traceback函数. 追溯函数不应对何时调用进行假设,因为Go的未来版本可能会进行其他调用.

将使用单个参数(指向结构的指针)调用symbolizer函数:

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语法,该结构将是

struct {
	uintptr_t PC;
	char*     File;
	uintptr_t Lineno;
	char*     Func;
	uintptr_t Entry;
	uintptr_t More;
	uintptr_t Data;
};

PC字段将是对追溯函数的调用返回的值.

第一次调用该函数以进行特定的追溯时,除PC以外的所有字段都将为0.如果可能,该函数应填写其他字段,如果该信息不可用,则将它们设置为0 / nil. 数据字段可用于存储所有有用信息. 如果此PC有更多信息,则应将"更多"字段设置为非零,否则为零. 如果"更多"设置为非零值,则将在同一台PC上再次调用该函数,并且该函数可能返回不同的信息(该信息专门用于内联函数). 如果"更多"为零,则将使用回溯中的下一个PC值调用该函数. 追溯完成后,将PC设置为零,将再次调用该函数; 这可用于释放任何信息. 每次调用都会将结构的字段设置为与返回时相同的值," More"字段为零时的PC字段除外. 该函数不得在调用之间保留struct指针的副本.

调用SetCgoTraceback时,version参数是函数期望接收的结构的版本号. 当前,该值必须为零.

符号器功能可能为零,在这种情况下,回溯功能的结果将显示为数字. 如果traceback函数为nil,则永远不会调用符号器函数. 上下文函数可以为nil,在这种情况下,仅在上下文字段设置为零的情况下调用回溯函数. 如果上下文函数为nil,则从Go到C到Go的调用将不会显示对调用堆栈的C部分的回溯.

SetCgoTraceback应该仅应调用一次,理想情况下应从init函数中调用一次.

func SetFinalizer

func SetFinalizer(obj interface{}, finalizer interface{})

SetFinalizer将与obj关联的终结器设置为提供的终结器函数. 当垃圾收集器找到带有关联的终结器的无法访问的块时,它将清除该关联并在单独的goroutine中运行finalizer(obj). 这使得obj可以再次访问,但是现在没有关联的终结器. 假设没有再次调用SetFinalizer,则下次垃圾回收器看到obj无法访问时,它将释放obj.

SetFinalizer(obj,nil)清除所有与obj相关的终结器.

参数obj必须是指向通过调用new,通过使用复合文字的地址或通过局部变量的地址分配的对象的指针. 参数终结器必须是一个接受单个参数的函数,可以将obj的类型分配给该参数,并且可以具有任意忽略的返回值. 如果这些都不成立,SetFinalizer可能会中止程序.

终结器按依赖关系顺序运行:如果A点位于B处,则都具有终结器,否则无法到达,则仅运行A终结器. 一旦释放了A,就可以运行B的终结器. 如果循环结构包括带有终结器的块,则不保证该循环会被垃圾回收,并且也不能保证终结器会运行,因为没有顺序会考虑到依赖项.

在程序无法再到达obj所指向的对象之后,终结器计划在任意时间运行. 无法保证终结器会在程序退出之前运行,因此通常它们仅对在长时间运行的程序期间释放与对象关联的非内存资源有用. 例如,当程序在不调用Close的情况下放弃os.File时,os.File对象可以使用终结器关闭关联的操作系统文件描述符,但是依靠终结器来刷新内存中的I将是一个错误. / O缓冲区,例如bufio.Writer,因为该缓冲区不会在程序退出时刷新.

如果* obj的大小为零字节,则不能保证终结器将运行.

不能保证终结程序将为在初始化程序中为程序包级变量分配的对象运行. 此类对象可以是链接程序分配的,而不是堆分配的.

一旦对象不可访问,终结器可能会运行. 为了正确使用终结器,程序必须确保可以访问该对象,直到不再需要该对象为止. 可以访问存储在全局变量中的对象,或者可以通过跟踪全局变量中的指针找到的对象. 对于其他对象,将该对象传递给KeepAlive函数的调用,以标记该函数中必须可到达该对象的最后一点.

例如,如果p指向包含文件描述符d的结构,并且p具有关闭该文件描述符的终结器,并且函数中对p的最后使用是对syscall的调用.Write(pd,buf,size ),则一旦程序进入syscall.Write,p可能无法访问. 终结器可能会在此时运行,关闭pd,导致syscall.Write失败,因为它正在写入关闭的文件描述符(或更糟的是,写入由不同的goroutine打开的完全不同的文件描述符). 为避免此问题,请在调用syscall.Write之后调用runtime.KeepAlive(p).

单个goroutine按顺序运行程序的所有终结器. 如果终结器必须运行很长时间,则应通过启动新的goroutine来完成.

func SetMutexProfileFraction 1.8

func SetMutexProfileFraction(rate int) int

SetMutexProfileFraction控制互斥配置文件中报告的互斥争用事件的比例. 平均报告1 /速率事件. 返回先前的费率.

要完全关闭性能分析,请通过速率0.要仅读取当前速率,请通过速率<0.(对于n> 1,采样的详细信息可能会更改.)

func Stack

func Stack(buf []byte, all bool) int

堆栈将调用goroutine的堆栈跟踪格式格式化为buf,并返回写入buf的字节数. 如果全部为真,则堆栈格式会将所有其他goroutine的跟踪信息堆叠到当前goroutine的跟踪信息之后的buf中.

func StartTrace 1.5

func StartTrace() error

StartTrace启用对当前进程的跟踪. 跟踪时,数据将被缓存并通过ReadTrace可用. 如果已经启用了跟踪,则StartTrace将返回错误. 大多数客户端应该使用运行时/跟踪软件包或测试软件包的-test.trace标志,而不是直接调用StartTrace.

func StopTrace 1.5

func StopTrace()

如果先前已启用StopTrace,则停止跟踪. StopTrace仅在完成对跟踪的所有读取之后才返回.

func ThreadCreateProfile

func ThreadCreateProfile(p []StackRecord) (n int, ok bool)

ThreadCreateProfile返回n,即线程创建配置文件中的记录数. 如果len(p)> = n,则ThreadCreateProfile将配置文件复制到p中并返回n,为true. 如果len(p)<n,则ThreadCreateProfile不会更改p并返回n,否则为false.

大多数客户端应该使用runtime / pprof包,而不是直接调用ThreadCreateProfile.

func UnlockOSThread

func UnlockOSThread()

UnlockOSThread撤消对LockOSThread的更早调用. 如果这将正在调用的goroutine上的活动LockOSThread调用数降为零,则将正在调用的goroutine从其固定的操作系统线程中断开连接. 如果没有活动的LockOSThread调用,则为空操作.

在调用UnlockOSThread之前,调用者必须确保OS线程适合运行其他goroutine. 如果调用者对线程状态进行了永久更改,从而影响其他goroutine,则不应调用此函数,因此将goroutine锁定在OS线程上,直到goroutine(因此线程)退出为止.

func Version

func Version() string

版本返回Go树的版本字符串. 它可以是构建时的提交哈希和日期,也可以是" go1.3"之类的发行标签.

type BlockProfileRecord 1.1

BlockProfileRecord描述了源自特定调用序列(堆栈跟踪)的阻止事件.

type BlockProfileRecord struct {
    Count  int64
    Cycles int64
    StackRecord
}

type Error

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()
}

type Frame 1.7

框架是框架为每个调用框架返回的信息.

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
    // contains filtered or unexported fields
}

type Frames 1.7

框架可用于获取调用者返回的一部分PC值的功能/文件/行信息.

type Frames struct {
    // contains filtered or unexported fields
}

Example

- more:true | runtime.Callers
- more:true | runtime_test.ExampleFrames.func1
- more:true | runtime_test.ExampleFrames.func2
- more:true | runtime_test.ExampleFrames.func3
- more:true | runtime_test.ExampleFrames

func CallersFrames 1.7

func CallersFrames(callers []uintptr) *Frames

CallersFrames提取了由Callers返回的PC值的一部分,并准备返回函数/文件/行信息. 在完成框架之前,请勿更改切片.

func (*Frames) Next 1.7

func (ci *Frames) Next() (frame Frame, more bool)

Next返回下一个呼叫者的帧信息. 如果更多为假,则没有更多的调用方("帧"值有效).

type Func

Func代表正在运行的二进制文件中的Go函数.

type Func struct {
    // contains filtered or unexported fields
}

func FuncForPC

func FuncForPC(pc uintptr) *Func

FuncForPC返回一个* Func,描述包含给定程序计数器地址的函数,否则为nil.

如果pc由于内联而表示多个函数,则它将返回* Func描述最内部的函数,但带有最外部的函数的条目.

func (*Func) Entry

func (f *Func) Entry() uintptr

Entry返回函数的入口地址.

func (*Func) FileLine

func (f *Func) FileLine(pc uintptr) (file string, line int)

FileLine返回与程序计数器pc对应的源代码的文件名和行号. 如果pc不是f中的程序计数器,则结果将不准确.

func (*Func) Name

func (f *Func) Name() string

名称返回函数的名称.

type MemProfileRecord

MemProfileRecord描述由特定调用序列(堆栈跟踪)分配的活动对象.

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 (*MemProfileRecord) InUseBytes

func (r *MemProfileRecord) InUseBytes() int64

InUseBytes返回使用中的字节数(AllocBytes-FreeBytes).

func (*MemProfileRecord) InUseObjects

func (r *MemProfileRecord) InUseObjects() int64

InUseObjects返回使用中的对象数(AllocObjects-FreeObjects).

func (*MemProfileRecord) Stack

func (r *MemProfileRecord) Stack() []uintptr

Stack返回与记录关联的堆栈跟踪,前缀为r.Stack0.

type MemStats

MemStats记录有关内存分配器的统计信息.

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 estimates 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 // Go 1.2

    // OtherSys is bytes of memory in miscellaneous off-heap
    // runtime allocations.
    OtherSys uint64 // Go 1.2

    // 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 // Go 1.4

    // 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 // Go 1.8

    // 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 // Go 1.5

    // 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
    }
}

type StackRecord

StackRecord描述单个执行堆栈.

type StackRecord struct {
    Stack0 [32]uintptr // stack trace for this record; ends at first 0 entry
}

func (*StackRecord) Stack

func (r *StackRecord) Stack() []uintptr

Stack返回与记录关联的堆栈跟踪,前缀为r.Stack0.

type TypeAssertionError

A TypeAssertionError explains a failed type assertion.

type TypeAssertionError struct {
    // contains filtered or unexported fields
}

func (*TypeAssertionError) Error

func (e *TypeAssertionError) Error() string

func (*TypeAssertionError) RuntimeError

func (*TypeAssertionError) RuntimeError()

Subdirectories

Name Synopsis
..
cgo Package cgo contains runtime support for code generated by the cgo tool.
debug 程序包调试包含用于程序在运行时进行自我调试的功能.
msan
pprof 软件包pprof以pprof可视化工具所需的格式写入运行时概要分析数据.
race 包竞争实现了数据竞争检测逻辑.
trace 包跟踪包含用于程序生成Go执行跟踪器跟踪的工具.

by  ICOPY.SITE