23 September 2017

Table of Contents


Package runtime contains operations that interact with Go's runtime system,
such as functions to control goroutines.

It also includes the low-level type information used by the reflect package; see reflect's documentation for the programmable interface to the run-time type system.

Environment Variables

The following environment variables ($name or %name%, depending on the host operating system) control the run-time behavior of Go programs. The meanings and use may change from release to release.

The GOGC variable sets the initial garbage collection target percentage.

A collection is triggered when the ratio of freshly allocated data to live data remaining after the previous collection reaches this percentage.

The default is GOGC=100.

Setting GOGC=off disables the garbage collector entirely. The runtime/debug package's SetGCPercent function allows changing this percentage at run time. See https://golang.org/pkg/runtime/debug/#SetGCPercent.

The GODEBUG variable controls debugging variables within the runtime. It is a comma-separated list of name=val pairs setting these named variables:

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.

The net and net/http packages also refer to debugging variables in GODEBUG. See the documentation for those packages for details.

The GOMAXPROCS variable limits the number of operating system threads that can execute user-level Go code simultaneously. There is no limit to the number of threads that can be blocked in system calls on behalf of Go code; those do not count against the GOMAXPROCS limit. This package's GOMAXPROCS function queries and changes the limit.

The GOTRACEBACK variable controls the amount of output generated when a Go program fails due to an unrecovered panic or an unexpected runtime condition. By default, a failure prints a stack trace for the current goroutine, eliding functions internal to the run-time system, and then exits with exit code 2. The failure prints stack traces for all goroutines if there is no current goroutine or the failure is internal to the run-time. GOTRACEBACK=none omits the goroutine stack traces entirely. GOTRACEBACK=single (the default) behaves as described above. GOTRACEBACK=all adds stack traces for all user-created goroutines. GOTRACEBACK=system is like “all” but adds stack frames for run-time functions and shows goroutines created internally by the run-time. GOTRACEBACK=crash is like “system” but crashes in an operating system-specific manner instead of exiting. For example, on Unix systems, the crash raises SIGABRT to trigger a core dump. For historical reasons, the GOTRACEBACK settings 0, 1, and 2 are synonyms for none, all, and system, respectively. The runtime/debug package's SetTraceback function allows increasing the amount of output at run time, but it cannot reduce the amount below that specified by the environment variable. See https://golang.org/pkg/runtime/debug/#SetTraceback.

The GOARCH, GOOS, GOPATH, and GOROOT environment variables complete the set of Go environment variables. They influence the building of Go programs (see https://golang.org/cmd/go and https://golang.org/pkg/go/build). GOARCH, GOOS, and GOROOT are recorded at compile time and made available by constants or functions in this package, but they do not influence the execution of the run-time system.


gc      Also known as cmd/compile.
gccgo   The gccgo front end, part of the GCC compiler suite.

const Compiler = "gc"
const GOARCH string = sys.GOARCH  // amd64
const GOOS string = sys.GOOS      // darwin


var MemProfileRate int = 512 * 1024

MemProfileRate 控制了内存分配因子用来记录和报告内存使用情况。
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(p []BlockProfileRecord) (n int, ok bool)

func Breakpoint()

func CPUProfile() []byte

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

func main() {
     for skip := 0; ; skip++ {
             pc, file, line, ok := runtime.Caller(skip)
             if !ok {
             fmt.Printf("skip = %v, pc = %v, file = %v, line = %v\n", skip, pc, file, line)
     // skip = 0, pc = 4198453, file = caller.go, line = 10
     // skip = 1, pc = 4280066, file = $(GOROOT)/src/runtime/proc.go, line = 185
     // skip = 2, pc = 4289712, file = $(GOROOT)/src/runtime/asm_amd64.s, line = 2197

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

func main() {
     pc := make([]uintptr, 1024)
     for skip := 0; ; skip++ {
             n := runtime.Callers(skip, pc)
             if n <= 0 {
             fmt.Printf("skip = %v, pc = %v\n", skip, pc[:n])
     // skip = 0, pc = [4304486 4198562 4280114 4289760]
     // skip = 1, pc = [4198562 4280114 4289760]
     // skip = 2, pc = [4280114 4289760]
     // skip = 3, pc = [4289760]


func main() {
     for skip := 0; ; skip++ {
             pc, file, line, ok := runtime.Caller(skip)
             if !ok {
             fmt.Printf("skip = %v, pc = %v, file = %v, line = %v\n", skip, pc, file, line)
     // skip = 0, pc = 17337538, file = /Users/sunx/proj/go/tour/test.go, line = 38
     // skip = 1, pc = 16938570, file = /usr/local/Cellar/go/1.8.3/libexec/src/runtime/proc.go, line = 185
     // skip = 2, pc = 17089729, file = /usr/local/Cellar/go/1.8.3/libexec/src/runtime/asm_amd64.s, line = 2197

     pc := make([]uintptr, 1024)
     for skip := 0; ; skip++ {
             n := runtime.Callers(skip, pc)
             if n <= 0 {
             fmt.Printf("skip = %v, pc = %v\n", skip, pc[:n])
     // skip = 0, pc = [16803169 17338015 16938570 17089729]
     // skip = 1, pc = [17338015 16938570 17089729]
     // skip = 2, pc = [16938570 17089729]
     // skip = 3, pc = [17089729]

func GC()

func GOMAXPROCS(n int) int

fmt.Printf("%v\n", runtime.GOMAXPROCS(0)) // 获取当前程序运行可以利用的 CPU 核数
fmt.Printf("%v\n", runtime.GOMAXPROCS(4)) // 设置当前程序运行可以利用的 CPU 核数

func GOROOT() string

func Goexit()

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

func Gosched()

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

func KeepAlive(interface{})

KeepAlive marks its argument as currently reachable. This ensures that the object is not freed, and its finalizer is not run, before the point in the program where KeepAlive is called.

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.
// No more uses of p after this point.

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 BlockProfileRecord struct {
      Count  int64
      Cycles int64

type Error

type Error interface {

      // RuntimeError is a no-op function but
      // serves to distinguish types that are runtime
      // errors from ordinary errors: a type is a
      // runtime error if it has a RuntimeError method.
      // RuntimeError 是一个无操作函数,它只用于区分是运行时错误还是一般错误:
      // 若一个类型拥有 RuntimeError 方法,它就是运行时错误。

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 say(str string) {
     pc, _, _, _ := runtime.Caller(0)
     f := runtime.FuncForPC(pc)
     fmt.Printf("%v\n", f.Name()) // main.say

func main() {
     pc, file, line, _ := runtime.Caller(0)
     fmt.Printf("%v %v %v\n", pc, file, line)

     f := runtime.FuncForPC(pc)
     fmt.Printf("%v\n", f.Name()) // main.main

func CallFuncName() string {
     var pc uintptr
     var ok bool
     if pc, _, _, ok = runtime.Caller(1); !ok {
             return ""
     return runtime.FuncForPC(pc).Name()

func say() {
     f := CallFuncName()
     fmt.Printf("say: %v\n", f) // say: main.say

func main() {
     f := CallFuncName()
     fmt.Printf("main: %v\n", f) // main: main.main

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