非常教程

Go参考手册

运行时 | runtime

运行时 | runtime

  • import "runtime"
  • 概况
  • 索引
  • 例子
  • 子目录

概况

Package runtime 包含与 Go 的运行时系统交互的操作,例如控制 goroutines 的函数。它还包括反映包使用的低级类型信息; 请参阅运行时类型系统的可编程接口的反射文档。

环境变量

以下环境变量($ 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.

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=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. 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 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

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.

net 和 net / http 软件包也指 GODEBUG 中的调试变量。有关详情,请参阅这些软件包的文档。

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

GOTRACEBACK 变量控制 Go 程序由于未发现的恐慌或意外的运行时情况而失败时产生的输出量。默认情况下,失败打印当前 goroutine 的堆栈跟踪,在运行系统内部隐藏函数,然后退出,退出代码2.如果没有当前的 goroutine 或者失败是失败,则打印所有 goroutine 的堆栈跟踪内部的运行时间。GOTRACEBACK = none 完全忽略 goroutine 堆栈轨迹。GOTRACEBACK = single(默认)的行为如上所述。GOTRACEBACK = 全部为所有用户创建的例程添加堆栈跟踪。GOTRACEBACK =系统类似于“全部”,但为运行时功能添加堆栈帧并显示运行时在内部创建的 goroutines 。GOTRACEBACK =崩溃与“系统”类似,但是以操作系统特定的方式崩溃而不是退出。例如,在 Unix 系统上,崩溃引发 SIGABRT 以触发核心转储。由于历史原因,GOTRACEBACK 设置0,1和2分别是 none,all 和 system 的同义词。运行时/调试包的 SetTraceback 函数允许在运行时增加输出量,但不能减少低于环境变量指定的量。请参阅https://golang.org/pkg/runtime/debug/#SetTraceback。但它不能减少低于环境变量指定的数量。请参阅https://golang.org/pkg/runtime/debug/#SetTraceback。但它不能减少低于环境变量指定的数量。请参阅https://golang.org/pkg/runtime/debug/#SetTraceback。

GOARCH,GOOS,GOPATH 和 GOROOT 环境变量完成 Go 环境变量的设置。他们影响 Go 程序的构建(请参阅https://golang.org/cmd/go和https://golang.org/pkg/go/build)。GOARCH,GOOS 和 GOROOT 是在编译时记录的,并且可以通过这个包中的常量或函数提供,但它们不会影响运行时系统的执行。

索引

  • 常量
  • 变量
  • 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 是运行程序的操作系统目标:达尔文,freebsd,linux 等等之一。

const GOOS string = sys.GOOS

变量

MemProfileRate 控制内存配置文件中记录和报告的内存分配部分。分析器旨在按分配的每个 MemProfileRate 字节对平均一个分配进行采样。

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

处理内存配置文件的工具假定配置文件速率在程序的整个生命周期内保持不变,并等于当前值。程序改变内存分析速率应该尽早执行一次,尽可能早地执行程序(例如,在 main 的开始处)。

var MemProfileRate int = 512 * 1024

func BlockProfileSource

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 BreakpointSource

func Breakpoint()

Breakpoint 执行断点陷阱。

func CPUProfileSource

func CPUProfile() []byte

CPUProfile 应急。它以前提供对由运行时生成的 pprof 格式配置文件的块的原始访问。生成该格式的细节已更改,因此此功能已被删除。

已弃用:请使用 runtime / pprof 软件包或 net / http / pprof 软件包中的处理程序,或者使用测试软件包的 -test.cpuprofile 标志。

func CallerSource

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

Caller 在调用的 goroutine 的堆栈上报告关于函数调用的文件和行号信息。参数跳过是要提升的堆栈帧的数量,其中0表示来电者的来电者。(由于历史原因,呼叫者和呼叫者之间跳过的含义不同)。返回值报告相应呼叫文件中的程序计数器,文件名和行号。如果无法恢复信息,则布尔值 ok 为 false 。

func CallersSource

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

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

要将这些 PC 转换为符号信息,如函数名称和行号,请​​使用 CallersFrames 。CallersFrames 占内置函数,并将返回程序计数器调整为调用程序计数器。不鼓励使用直接对返回的 PC 片进行迭代,因为在任何返回的 PC 上使用 FuncForPC,因为这些不能计入内联或返回程序计数器调整。

func GCSource

func GC()

GC 运行垃圾收集并阻塞调用方,直到垃圾收集完成。它也可能会阻止整个程序。

func GOMAXPROCSSource

func GOMAXPROCS(n int) int

GOMAXPROCS 设置可以同时执行的最大 CPU 数并返回以前的设置。如果 n <1,它不会改变当前设置。本地机器上的逻辑 CPU 数量可以通过 NumCPU 查询。当调度程序改进时,此调用将消失。

func GOROOTSource

func GOROOT() string

GOROOT 返回 Go 树的根。它使用 GOROOT 环境变量(如果已设置),或者使用 Go 构建期间使用的根。

func GoexitSource

func Goexit()

Goexit 终止调用它的 goroutine 。没有其他 goroutine 受到影响。Goexit 在终止 goroutine 之前运行所有延迟调用。因为 Goexit 并不恐慌,但是,这些延迟函数中的任何恢复调用都将返回 nil 。

在主要的例程中调用 Goexit 会终止那个没有 func 主要返回的例程。由于 func main 没有返回,程序继续执行其他 goroutines 。如果所有其他 goutoutines 退出,程序崩溃。

func GoroutineProfileSource

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

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

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

func GoschedSource

func Gosched()

Gosched 产生处理器,允许其他 goroutine 运行。它不会暂停当前的 goroutine,因此执行会自动恢复。go:nosplit

func KeepAliveSource

func KeepAlive(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 开始时运行。读取,在 syscall.Read 进行实际系统调用之前关闭文件描述符。

func LockOSThreadSource

func LockOSThread()

LockOSThread 将调用的 goroutine 连接到当前的操作系统线程。在调用 goroutine 退出或调用 UnlockOSThread 之前,它将始终在该线程中执行,并且没有其他 goroutine 可以执行。

func MemProfileSource

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 MutexProfileSource

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 NumCPUSource

func NumCPU() int

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

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

func NumCgoCallSource

func NumCgoCall() int64

NumCgoCall 返回当前进程所做的 cgo 调用的数量。

func NumGoroutineSource

func NumGoroutine() int

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

func ReadMemStatsSource

func ReadMemStats(m *MemStats)

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

返回的内存分配程序统计信息在调用 ReadMemStats 时是最新的。这与堆配置文件形成鲜明对比,堆配置文件是最近完成的垃圾回收周期的快照。

func ReadTraceSource

func ReadTrace() []byte

ReadTrace 返回下一块二进制跟踪数据,阻塞直到数据可用。如果跟踪关闭,并且所有数据已经​​返回,则 ReadTrace 返回 nil 。调用者必须在再次调用 ReadTrace 之前复制返回的数据。ReadTrace 必须一次从一个 goroutine 调用。

func SetBlockProfileRateSource

func SetBlockProfileRate(rate int)

SetBlockProfileRate 控制阻塞配置文件中报告的 goroutine 阻塞事件的一小部分。分析器旨在对阻塞的每个速率纳秒的平均阻塞事件进行采样。

要在配置文件中包含每个阻塞事件,传递率= 1.要完全关闭分析,传递率<= 0。

func SetCPUProfileRateSource

func SetCPUProfileRate(hz int)

SetCPUProfileRate 将 CPU 分析速率设置为每秒 hz 个样本。如果 hz <= 0,SetCPUProfileRate 关闭分析。如果分析器处于打开状态,则不必先关闭速率,否则无法更改速率。

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

func SetCgoTracebackSource

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

SetCgoTraceback 记录三个 C 函数,用于从 C 代码收集追溯信息并将该追溯信息转换为符号信息。打印使用 cgo 的程序的堆栈轨迹时使用这些。

追踪和上下文功能可以从信号处理程序中调用,因此必须仅使用异步信号安全功能。当程序崩溃时,可能会调用符号函数,因此必须谨慎使用内存。没有任何功能可以回拨到 Go 中。

上下文函数将被调用一个参数,一个指向结构体的指针:

struct {
	Context uintptr
}

在 C 语法中,这个结构将会是

struct {
	uintptr_t Context;
};

如果 Context 字段为0,则会调用上下文函数来记录当前的回溯上下文。它应该在上下文字段中记录关于当前执行点的任何信息,以便稍后生成堆栈跟踪,可能是堆栈指针和 PC 。在这种情况下,上下文函数将从 C 代码调用。

如果上下文字段不是0,那么它是前一次调用上下文函数返回的值。这种情况在不再需要上下文时被调用; 也就是说,Go 代码返回到其 C 代码调用方时。这允许上下文功能释放任何关联的资源。

尽管上下文函数在被调用时记录一个完整的堆栈跟踪是正确的,并且简单地将其拷贝到回溯函数中,但在典型的程序中,上下文函数将被多次调用,而不会记录那个回溯上下文。在对上下文函数的调用中记录完整的堆栈跟踪可能效率不高。

traceback 函数将被调用一个参数,一个指向 struct 的指针:

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

在 C 语法中,这个结构将会是

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

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

否则,上下文将成为之前由上下文函数调用返回的值。回溯函数应该从程序执行中的保存点中收集一个堆栈跟踪。回溯函数可以从记录上下文的执行线程以外的执行线程调用,但只有在上下文已知是有效且不变的情况下。回溯函数也可以在记录上下文的同一个线程的调用堆栈中调用得更深。回溯函数可以用相同的上下文值多次调用; 如果可能的话,第一次调用特定的上下文值时,缓存结果通常是适当的。

如果从 Unix 系统的信号处理程序调用回溯函数,则 SigContext 将作为传递给信号处理程序的信号上下文参数(C ucontext_t * 转换为 uintptr_t)。这可能用于在发生信号的位置开始追踪。如果追踪函数没有从信号处理程序调用,则 SigContext 将为零。

Buf 是追踪信息应该存储的地方。它应该是 PC 值,例如 Buf0 是调用者的 PC,Buf1 是该函数的调用者的 PC,等等。最大值是要存储的最大条目数。该函数应该存储一个零来表示堆栈的顶部,或者调用者位于不同的堆栈上,大概是一个 Go 堆栈。

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

符号函数将用一个参数来调用,一个指向 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 语法中,这个结构将会是

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 有更多信息,则 More 字段应设置为非零,否则为零。如果更多设置为非零,该功能将再次用同一台 PC 调用,并可能返回不同的信息(这是为了与内联函数一起使用)。如果 More 为零,则将使用回溯中的下一个 PC 值调用该函数。当回溯完成时,PC 将被设置为零,函数将再次被调用; 这可能被用来释放任何信息。每次调用都会将结构集的字段设置为与返回时相同的值,但“More”字段为零时的 PC 字段除外。该函数不能在调用之间保留结构体指针的副本。

当调用 SetCgoTraceback 时,version 参数是函数期望接收的结构的版本号。目前这一定是零。

符号函数可能为零,在这种情况下,回溯函数的结果将显示为数字。如果回溯函数为零,则不会调用符号函数。上下文函数可能为零,在这种情况下,只有在上下文字段设置为零的情况下才会调用回溯函数。如果上下文函数为零,则从 Go 到 C 到 Go 的调用不会显示调用堆栈 C 部分的回溯。

SetCgoTraceback 应该只被调用一次,理想情况是从一个 init 函数中调用。

func SetFinalizerSource

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

SetFinalizer 将与 obj 关联的终结器设置为提供的终结器函数。当垃圾收集器发现具有关联终结器的不可达块时,它将清除关联并在单独的 goroutine 中运行终结器(obj)。这使 obj 再次可达,但现在没有关联的终结器。假设没有再次调用 SetFinalizer,下次垃圾收集器看到 obj 无法访问时,它将释放 obj 。

SetFinalizer(obj,nil)清除与 obj 关联的任何终结器。

参数 obj 必须是指向通过调用 new 分配的对象的指针,通过获取组合文字的地址,或者通过获取局部变量的地址。参数终结器必须是一个函数,它接受一个可以赋予 obj 类型的参数,并且可以有任意忽略的返回值。如果其中任何一个不成立,SetFinalizer 可能会中止该程序。

终结器以依赖顺序运行:如果 A 在 B 点,两者都有终结器,否则无法访问,只有 A 的终结器运行; 一旦 A 被释放,B 的终结器可以运行。如果循环结构包含带终结器的块,则不保证该循环被垃圾收集,并且终结器不能保证运行,因为没有遵从依赖关系的排序。

obj 的终结器计划在 obj 变得无法访问之后的某个任意时间运行。不能保证在程序退出之前终结器会运行,因此通常它们仅用于在长时间运行的程序期间释放与对象关联的非内存资源。例如,当程序放弃 os.File 而不调用 Close 时,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 SetMutexProfileFractionSource

func SetMutexProfileFraction(rate int) int

SetMutexProfileFraction 控制互斥量配置文件中报告的互斥量争用事件的分数。平均报告1个费率事件。之前的费率将返回。

要完全关闭分析,通过率为0.要只读取当前的速率,通过率为-1。(对于 n> 1,采样的细节可能会改变。)

func StackSource

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

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

func StartTraceSource

func StartTrace() error

StartTrace 支持跟踪当前进程。在追踪时,数据将通过 ReadTrace 进行缓冲并提供。如果跟踪已启用,则 StartTrace 将返回错误。大多数客户端应该使用 runtime/trace package 或测试包的 -test.trace 标志,而不是直接调用 StartTrace 。

func StopTraceSource

func StopTrace()

StopTrace 停止跟踪,如果它以前启用。在跟踪的所有读取完成后,StopTrace 才会返回。

func ThreadCreateProfileSource

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 UnlockOSThreadSource

func UnlockOSThread()

UnlockOSThread 从其固定的操作系统线程中解除调用的 goroutine 。如果调用的 goroutine 没有调用 LockOSThread,则 UnlockOSThread 是无操作的。

func VersionSource

func Version() string

版本返回 Go 树的版本字符串。它可以是构建时的提交 hash 和日期,也可以是发布标签,如“go1.3”。

type BlockProfileRecordSource

BlockProfileRecord 描述了在特定的调用序列(堆栈跟踪)发起的阻塞事件。

type BlockProfileRecord struct {
        Count  int64
        Cycles int64
        StackRecord
}

type ErrorSource

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 FrameSource

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
}

type FramesSource

帧可以用来获取由呼叫者返回的 PC 片段的功能/文件/线路信息。

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

package main

import (
	"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 CallersFramesSource

func CallersFrames(callers []uintptr) *Frames

CallersFrames 获取由调用者返回的一部分 PC 值,并准备返回函数/文件/行信息。在完成帧之前,不要更改切片。

func (*Frames) NextSource

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

Next 返回下一个调用者的帧信息。如果 more为false,则不再有主叫方(Frame 值有效)。

type FuncSource

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

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

func FuncForPCSource

func FuncForPC(pc uintptr) *Func

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

如果 pc 由于内联而代表多个函数,它将返回描述最外层函数的 * Func 。

func (*Func) EntrySource

func (f *Func) Entry() uintptr

Entry 返回函数的入口地址。

func (*Func) FileLineSource

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

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

func (*Func) NameSource

func (f *Func) Name() string

Name 返回函数的名称。

type MemProfileRecordSource

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) InUseBytesSource

func (r *MemProfileRecord) InUseBytes() int64

InUseBytes 返回正在使用的字节数(AllocBytes - FreeBytes)。

func (*MemProfileRecord) InUseObjectsSource

func (r *MemProfileRecord) InUseObjects() int64

InUseObjects 返回正在使用的对象的数量(AllocObjects - FreeObjects)。

func (*MemProfileRecord) StackSource

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

Stack 返回与记录相关的堆栈跟踪,它是 r.Stack0 的前缀。

type MemStatsSource

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

type StackRecordSource

StackRecord 描述了一个执行堆栈。

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

func (*StackRecord) StackSource

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

Stack 返回与记录相关的堆栈跟踪,它是 r.Stack0 的前缀。

type TypeAssertionErrorSource

TypeAssertionError 解释失败的类型断言。

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

func (*TypeAssertionError) ErrorSource

func (e *TypeAssertionError) Error() string

func (*TypeAssertionError) RuntimeErrorSource

func (*TypeAssertionError) RuntimeError()

Subdirectories

Name

Synopsis

cgo

Package cgo 包含由 cgo 工具生成的代码的运行时支持。

debug

程序包调试包含程序在运行时进行调试的功能。

internal/sys

包sys包含运行时使用的系统和配置以及特定于体系结构的常量。

pprof

软件包 pprof 以 pprof 可视化工具所期望的格式写入运行时分析数据。

race

包比赛实施数据竞赛检测逻辑。

trace

执行追踪器。

运行时 | runtime
运行时 | runtime 详细
runtime/cgo 详细
调试 | runtime/debug 详细
runtime/internal/sys 详细
runtime/pprof 详细
竞争 | runtime/race 详细
执行追踪器 | runtime/trace 详细
Go

Go 是一种编译型语言,它结合了解释型语言的游刃有余,动态类型语言的开发效率,以及静态类型的安全性。它也打算成为现代的,支持网络与多核计算的语言。要满足这些目标,需要解决一些语言上的问题:一个富有表达能力但轻量级的类型系统,并发与垃圾回收机制,严格的依赖规范等等。这些无法通过库或工具解决好,因此Go也就应运而生了。

主页 https://golang.org/
源码 https://go.googlesource.com/go
发布版本 1.9.2

Go目录

1.档案 | archive
2.缓冲区 | bufio
3.内置 | builtin
4.字节 | bytes
5.压缩 | compress
6.容器 | container
7.上下文 | context
8.加密 | crypto
9.数据库 | database
10.调试 | debug
11.编码 | encoding
12.错误 | errors
13. expvar
14.flag
15. fmt
16. go
17.散列 | hash
18.html
19.图像 | image
20.索引 | index
21.io
22.日志 | log
23.数学 | math
24. math/big
25.math/bits
26.math/cmplx
27.math/rand
28.拟态 | mime
29.net
30.net/http
31. net/mail
32. net/rpc
33.net/smtp
34. net/textproto
35. net/url
36.os
37.路径 | path
38.插件 | plugin
39.反射 | reflect
40.正则表达式 | regexp
41.运行时 | runtime
42.排序算法 | sort
43.转换 | strconv
44.字符串 | strings
45.同步 | sync
46.系统调用 | syscall
47.测试 | testing
48.文本 | text
49.时间戳 | time
50.unicode
51.不安全性 | unsafe
52.Go 语言数据类型
53.Go 语言基础语法
54.Go 语言结构
55.Go 语言 select 语句
56.Go 语言 switch 语句
57.Go 语言 if 语句嵌套
58.Go 语言 if…else 语句
59.Go 语言 if 语句
60.Go 语言运算符
61.Go 语言常量
62.Go 语言函数闭包
63.Go 语言函数作为实参
64.Go 语言函数引用传递值
65.Go 语言函数值传递值
66.Go 语言函数
67.Go 语言 goto 语句
68.Go 语言 continue 语句
69.Go 语言 break 语句
70.Go 语言循环嵌套
71.Go 语言 for 循环
72.Go 语言结构体
73.Go 语言指针作为函数参数
74.Go 语言指向指针的指针
75.Go 语言指针数组
76.Go 语言指针
77.Go 语言向函数传递数组
78.Go 语言多维数组
79.Go 语言变量作用域
80.Go 语言函数方法
81.Go 错误处理
82.Go 语言接口
83.Go 语言类型转换
84.Go 语言递归函数
85.Go 语言Map(集合)
86.Go 语言范围(Range)
87.Go 语言切片(Slice)
88.Go 并发
89.Go fmt.Sprintf 格式化字符串