...

Package runtime

import "runtime"
概览
索引
子目录

概览 ▾

TODO(osc): 需更新 runtime 包含与Go的运行时系统进行交互的操作,例如用于控制Go程的函数. 它也包括用于 reflect 包的底层类型信息;运行时类型系统的可编程接口见 reflect 文档。

环境变量

以下环境变量($name 或 %name%, 取决于宿主操作系统)控制了Go程序的运行时行为。 其意义与使用方法在发行版之间可能有所不同。

GOGC 变量用于设置初始垃圾回收的目标百分比。从上次回收后开始,当新分配数据的比例占到剩余实时数据的此百分比时, 就会再次触发回收。默认为 GOGC=100。要完全关闭垃圾回收器,需设置 GOGC=off。runtime/debug 包的 SetGCPercent 函数允许在运行时更改此百分比。 详见 http://zh.golanger.com/pkg/runtime/debug/#SetGCPercent

GOGCTRACE 变量用于控制来自垃圾回收器的调试输出。设置 GOGCTRACE=1 会使垃圾回收器发出 每一次回收所产生的单行标准错误输出、概述回收的内存量以及暂停的时长。设置 GOGCTRACE=2 不仅会发出同样的概述,还会重复每一次回收。

GOMAXPROCS 变量用于限制可同时执行的用户级Go代码所产生的操作系统线程数。对于Go代码所代表的系统调用而言, 可被阻塞的线程则没有限制;它们不计入 GOMAXPROCS 的限制。本包中的 GOMAXPROCS 函数可查询并更改此限制。

GOTRACEBACK 用于控制因未恢复的恐慌或意外的运行时状况导致Go程序运行失败时所产生的输出量。 默认情况下,失败会为每个现有的Go程打印出栈跟踪,省略运行时系统的内部函数,并以退出码 2 退出。 若 GOTRACEBACK=0,则每个Go程的栈跟踪都会完全省略。 若 GOTRACEBACK=1,则采用默认的行为。 若 GOTRACEBACK=2,则每个Go程的栈跟踪,包括运行时函数都会输出。 若 GOTRACEBACK=crash,则每个Go程的栈跟踪,包括运行时函数,都会输出, 此外程序可能以操作系统特定的方式崩溃而非退出。例如,在Unix系统上,程序会发出 SIGABRT 信号,从而触发内核转储。

GOARCH、GOOS、GOPATH 和 GOROOT 环境变量均为Go的环境变量。它们影响了Go程序的构建 (详见 http://golang.org/cmd/gohttp://golang.org/pkg/go/build)。 GOARCH、GOOS 和 GOROOT 会在编译时被记录,并使该包中的常量或函数变得可用, 但它们并不影响运行时系统的执行。

索引 ▾

包文件

alg.go arch1_amd64.go arch1_arm64.go arch1_ppc64.go arch1_ppc64le.go arch_amd64.go arch_arm64.go arch_ppc64.go arch_ppc64le.go atomic_amd64x.go atomic_arm64.go atomic_pointer.go cgo.go cgocall.go cgocallback.go chan.go compiler.go complex.go cpuprof.go cputicks.go debug.go defs_darwin_arm64.go defs_linux_amd64.go defs_linux_arm64.go defs_linux_ppc64.go defs_linux_ppc64le.go env_posix.go error.go extern.go hash64.go hashmap.go hashmap_fast.go heapdump.go iface.go lfstack.go lfstack_amd64.go lfstack_darwin_arm64.go lfstack_linux_arm64.go lock_futex.go malloc.go mbarrier.go mbitmap.go mcache.go mcentral.go mem_linux.go mfinal.go mfixalloc.go mgc.go mgcmark.go mgcsweep.go mgcwork.go mheap.go mprof.go msize.go mstats.go netpoll.go netpoll_epoll.go os1_linux.go os2_linux.go os_darwin_arm64.go os_linux.go os_linux_arm64.go panic.go panic1.go parfor.go print1.go print1_write.go proc.go proc1.go race0.go rdebug.go rune.go runtime.go runtime1.go runtime2.go select.go sema.go signal1_unix.go signal_amd64x.go signal_arm64.go signal_darwin_arm64.go signal_linux.go signal_linux_amd64.go signal_linux_arm64.go signal_unix.go sigpanic_unix.go sigqueue.go slice.go softfloat64.go sqrt.go stack1.go stack2.go string.go string1.go stubs.go stubs2.go symtab.go sys_arm64.go sys_x86.go time.go trace.go traceback.go type.go typekind.go typekind1.go unaligned1.go vdso_linux_amd64.go wbfat.go zgoarch_amd64.go zgoarch_arm64.go zgoarch_ppc64.go zgoarch_ppc64le.go zgoos_linux.go

常量

const Compiler = "gc"

Compiler 为构建了可运行二进制文件的编译工具链。已知的工具链为:

go       code.google.com/p/go 上的 5g/6g/8g 编译器套件。
gccgo    gccgo前端,GCC编译器条件的一部分。
const GOARCH string = theGoarch

GOARCH 为所运行程序的目标架构: 386、amd64 或 arm。

const GOOS string = theGoos

GOOS 为所运行程序的目标操作系统: darwin、freebsd或linux等等。

const (
    _ selectDir = iota
)

变量

var MemProfileRate int = 512 * 1024

MemProfileRate controls the fraction of memory allocations that are recorded and reported in the memory profile. The profiler aims to sample an average of one allocation per MemProfileRate bytes allocated.

To include every allocated block in the profile, set MemProfileRate to 1. To turn off profiling entirely, set MemProfileRate to 0.

The tools that process the memory profiles assume that the profile rate is constant across the lifetime of the program and equal to the current value. Programs that change the memory profiling rate should do so just once, as early as possible in the execution of the program (for example, at the beginning of main).

func BlockProfile

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

BlockProfile returns n, the number of records in the current blocking profile. If len(p) >= n, BlockProfile copies the profile into p and returns n, true. If len(p) < n, BlockProfile does not change p and returns n, false.

Most clients should use the runtime/pprof package or the testing package's -test.blockprofile flag instead of calling BlockProfile directly.

func Breakpoint

func Breakpoint()

Breakpoint executes a breakpoint trap.

func CPUProfile

func CPUProfile() []byte

CPUProfile returns the next chunk of binary CPU profiling stack trace data, blocking until data is available. If profiling is turned off and all the profile data accumulated while it was on has been returned, CPUProfile returns nil. The caller must save the returned data before calling CPUProfile again.

Most clients should use the runtime/pprof package or the testing package's -test.cpuprofile flag instead of calling CPUProfile directly.

func Caller

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

Caller 报告关于调用Go程的栈上的函数调用的文件和行号信息。 实参 skip 为占用的栈帧数,若为0则表示 Caller 的调用者。(由于历史原因,skip 的意思在 Caller 和 Callers 中并不相同。)返回值报告程序计数器, 文件名及对应调用的文件中的行号。若无法获得信息,布尔值 ok 即为 false。

func Callers

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

Callers 把调用它的Go程栈上函数请求的返回程序计数器填充到切片 pc 中。 实参 skip 为开始在 pc 中记录之前所要跳过的栈帧数,若为 0 则表示 Callers 自身的栈帧, 若为 1 则表示 Callers 的调用者。它返回写入到 pc 中的项数。

注意,由于每个切片项 pc[i] 都是一个返回程序计数器,因此查找 pc[i] 的文件和行(例如,使用 (*Func).FileLine)将会在该调用之后立即返回该指令所在的文件和行号。 要查找该调用本身所在的文件和行号,请使用 pc[i]-1。此规则的一个例外是,若 pc[i-1] 对应于函数 runtime.sigpanic,那么 pc[i] 就是失败指令的程序计数器,因此应当不通过任何减法来使用。

func GC

func GC()

GC runs a garbage collection.

func GOMAXPROCS

func GOMAXPROCS(n int) int

GOMAXPROCS 设置可同时使用执行的最大CPU数,并返回先前的设置。 若 n < 1,它就不会更改当前设置。本地机器的逻辑CPU数可通过 NumCPU 查询。 当调度器改进后,此调用将会消失。

func GOROOT

func GOROOT() string

GOROOT 返回Go目录树的根目录。 若设置了GOROOT环境变量,就会使用它,否则就会将Go的构建目录作为根目录

func Goexit

func Goexit()

Goexit terminates the goroutine that calls it. No other goroutine is affected. Goexit runs all deferred calls before terminating the goroutine. Because Goexit is not panic, however, any recover calls in those deferred functions will return nil.

Calling Goexit from the main goroutine terminates that goroutine without func main returning. Since func main has not returned, the program continues execution of other goroutines. If all other goroutines exit, the program crashes.

func GoroutineProfile

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

GoroutineProfile returns n, the number of records in the active goroutine stack profile. If len(p) >= n, GoroutineProfile copies the profile into p and returns n, true. If len(p) < n, GoroutineProfile does not change p and returns n, false.

Most clients should use the runtime/pprof package instead of calling GoroutineProfile directly.

func Gosched

func Gosched()

Gosched yields the processor, allowing other goroutines to run. It does not suspend the current goroutine, so execution resumes automatically.

func LockOSThread

func LockOSThread()

LockOSThread wires the calling goroutine to its current operating system thread. Until the calling goroutine exits or calls UnlockOSThread, it will always execute in that thread, and no other goroutine can.

func MemProfile

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

MemProfile returns n, the number of records in the current memory profile. If len(p) >= n, MemProfile copies the profile into p and returns n, true. If len(p) < n, MemProfile does not change p and returns n, false.

If inuseZero is true, the profile includes allocation records where r.AllocBytes > 0 but r.AllocBytes == r.FreeBytes. These are sites where memory was allocated, but it has all been released back to the runtime.

Most clients should use the runtime/pprof package or the testing package's -test.memprofile flag instead of calling MemProfile directly.

func NumCPU

func NumCPU() int

NumCPU 返回本地机器的逻辑CPU数。

func NumCgoCall

func NumCgoCall() int64

NumCgoCall 返回由当前进程创建的cgo调用数。

func NumGoroutine

func NumGoroutine() int

NumGoroutine 返回当前存在的Go程数。

func ReadMemStats

func ReadMemStats(m *MemStats)

ReadMemStats populates m with memory allocator statistics.

func ReadTrace

func ReadTrace() []byte

ReadTrace returns the next chunk of binary tracing data, blocking until data is available. If tracing is turned off and all the data accumulated while it was on has been returned, ReadTrace returns nil. The caller must copy the returned data before calling ReadTrace again. ReadTrace must be called from one goroutine at a time.

func SetBlockProfileRate

func SetBlockProfileRate(rate int)

SetBlockProfileRate controls the fraction of goroutine blocking events that are reported in the blocking profile. The profiler aims to sample an average of one blocking event per rate nanoseconds spent blocked.

To include every blocking event in the profile, pass rate = 1. To turn off profiling entirely, pass rate <= 0.

func SetCPUProfileRate

func SetCPUProfileRate(hz int)

SetCPUProfileRate sets the CPU profiling rate to hz samples per second. If hz <= 0, SetCPUProfileRate turns off profiling. If the profiler is on, the rate cannot be changed without first turning it off.

Most clients should use the runtime/pprof package or the testing package's -test.cpuprofile flag instead of calling SetCPUProfileRate directly.

func SetFinalizer

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

SetFinalizer 为 f 设置与 x 相关联的终结器。 当垃圾回收器找到一个无法访问的块及与其相关联的终结器时,就会清理该关联, 并在一个独立的Go程中运行f(x)。这会使 x 再次变得可访问,但现在没有了相关联的终结器。 假设 SetFinalizer 未被再次调用,当下一次垃圾回收器发现 x 无法访问时,就会释放 x。

SetFinalizer(x, nil) 会清理任何与 x 相关联的终结器。

实参 x 必须是一个对象的指针,该对象通过调用新的或获取一个复合字面地址来分配。 实参 f 必须是一个函数,该函数获取一个 x 的类型的单一实参,并拥有可任意忽略的返回值。 只要这些条件有一个不满足,SetFinalizer 就会跳过该程序。

终结器按照依赖顺序运行:若 A 指向 B,则二者都有终结器,当只有 A 的终结器运行时, 它们才无法访问;一旦 A 被释放,则 B 的终结器便可运行。若循环依赖的结构包含块及其终结器, 则该循环并不能保证被垃圾回收,而其终结器并不能保证运行,这是因为其依赖没有顺序。

x 的终结器预定为在 x 无法访问后的任意时刻运行。无法保证终结器会在程序退出前运行, 因此它们通常只在长时间运行的程序中释放一个关联至对象的非内存资源时使用。 例如,当程序丢弃 os.File 而没有调用 Close 时,该 os.File 对象便可使用一个终结器 来关闭与其相关联的操作系统文件描述符,但依赖终结器去刷新一个内存中的I/O缓存是错误的, 因为该缓存不会在程序退出时被刷新。

一个程序的单个Go程会按顺序运行所有的终结器。若某个终结器需要长时间运行, 它应当通过开始一个新的Go程来继续。 TODO(osc): 仍需校对及语句优化

func Stack

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

Stack formats a stack trace of the calling goroutine into buf and returns the number of bytes written to buf. If all is true, Stack formats stack traces of all other goroutines into buf after the trace for the current goroutine.

func StartTrace

func StartTrace() error

StartTrace enables tracing for the current process. While tracing, the data will be buffered and available via ReadTrace. StartTrace returns an error if tracing is already enabled. Most clients should use the runtime/pprof package or the testing package's -test.trace flag instead of calling StartTrace directly.

func StopTrace

func StopTrace()

StopTrace stops tracing, if it was previously enabled. StopTrace only returns after all the reads for the trace have completed.

func ThreadCreateProfile

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

ThreadCreateProfile returns n, the number of records in the thread creation profile. If len(p) >= n, ThreadCreateProfile copies the profile into p and returns n, true. If len(p) < n, ThreadCreateProfile does not change p and returns n, false.

Most clients should use the runtime/pprof package instead of calling ThreadCreateProfile directly.

func UnlockOSThread

func UnlockOSThread()

UnlockOSThread unwires the calling goroutine from its fixed operating system thread. If the calling goroutine has not called LockOSThread, UnlockOSThread is a no-op.

func Version

func Version() string

Version 返回Go目录树的版本字符串。 它一般是一个提交散列值及其构建时间,也可能是一个类似于 "go1.3" 的发行标注。

type BlockProfileRecord

type BlockProfileRecord struct {
    Count  int64
    Cycles int64
    StackRecord
}

BlockProfileRecord describes blocking events originated at a particular call sequence (stack trace).

type 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 是一个无操作函数,它只用于区分是运行时错误还是一般错误:
    // 若一个类型拥有 RuntimeError 方法,它就是运行时错误。
    RuntimeError()
}

Error 接口用于标识运行时错误。

type Func

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

A Func represents a Go function in the running binary.

func FuncForPC

func FuncForPC(pc uintptr) *Func

FuncForPC returns a *Func describing the function that contains the given program counter address, or else nil.

func (*Func) Entry

func (f *Func) Entry() uintptr

Entry returns the entry address of the function.

func (*Func) FileLine

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

FileLine returns the file name and line number of the source code corresponding to the program counter pc. The result will not be accurate if pc is not a program counter within f.

func (*Func) Name

func (f *Func) Name() string

Name returns the name of the function.

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

A MemProfileRecord describes the live objects allocated by a particular call sequence (stack trace).

func (*MemProfileRecord) InUseBytes

func (r *MemProfileRecord) InUseBytes() int64

InUseBytes returns the number of bytes in use (AllocBytes - FreeBytes).

func (*MemProfileRecord) InUseObjects

func (r *MemProfileRecord) InUseObjects() int64

InUseObjects returns the number of objects in use (AllocObjects - FreeObjects).

func (*MemProfileRecord) Stack

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

Stack returns the stack trace associated with the record, a prefix of r.Stack0.

type MemStats

type MemStats struct {
    // General statistics.
    Alloc      uint64 // bytes allocated and not yet freed
    TotalAlloc uint64 // bytes allocated (even if freed)
    Sys        uint64 // bytes obtained from system (sum of XxxSys below)
    Lookups    uint64 // number of pointer lookups
    Mallocs    uint64 // number of mallocs
    Frees      uint64 // number of frees

    // Main allocation heap statistics.
    HeapAlloc    uint64 // bytes allocated and not yet freed (same as Alloc above)
    HeapSys      uint64 // bytes obtained from system
    HeapIdle     uint64 // bytes in idle spans
    HeapInuse    uint64 // bytes in non-idle span
    HeapReleased uint64 // bytes released to the OS
    HeapObjects  uint64 // total number of allocated objects

    // Low-level fixed-size structure allocator statistics.
    //	Inuse is bytes used now.
    //	Sys is bytes obtained from system.
    StackInuse  uint64 // bytes used by stack allocator
    StackSys    uint64
    MSpanInuse  uint64 // mspan structures
    MSpanSys    uint64
    MCacheInuse uint64 // mcache structures
    MCacheSys   uint64
    BuckHashSys uint64 // profiling bucket hash table
    GCSys       uint64 // GC metadata
    OtherSys    uint64 // other system allocations

    // Garbage collector statistics.
    NextGC       uint64 // next collection will happen when HeapAlloc ≥ this amount
    LastGC       uint64 // end time of last collection (nanoseconds since 1970)
    PauseTotalNs uint64
    PauseNs      [256]uint64 // circular buffer of recent GC pause durations, most recent at [(NumGC+255)%256]
    PauseEnd     [256]uint64 // circular buffer of recent GC pause end times
    NumGC        uint32
    EnableGC     bool
    DebugGC      bool

    // Per-size allocation statistics.
    // 61 is NumSizeClasses in the C code.
    BySize [61]struct {
        Size    uint32
        Mallocs uint64
        Frees   uint64
    }
}

A MemStats records statistics about the memory allocator.

type StackRecord

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

A StackRecord describes a single execution stack.

func (*StackRecord) Stack

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

Stack returns the stack trace associated with the record, a prefix of r.Stack0.

type TypeAssertionError

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

TypeAssertionError 用于阐明失败的类型断言。

func (*TypeAssertionError) Error

func (e *TypeAssertionError) Error() string

func (*TypeAssertionError) RuntimeError

func (*TypeAssertionError) RuntimeError()

子目录

名称      摘要
..
cgo      cgo 包含有 cgo 工具生成的代码的运行时支持.
debug      debug 包含有程序在运行时调试其自身的功能.
pprof      pprof 包按照可视化工具 pprof 所要求的格式写出运行时分析数据.
race      race 包实现了数据竞争检测逻辑.