Golang的关键字defer的使用方法

目录
  • 核心思想
  • defer链
  • 源码分析
  • 优化

核心思想

在defer出现的地方插入了指令CALL runtime.deferproc,在函数返回的地方插入了CALL runtime.deferreturn。goroutine的控制结构中,有一张表记录defer,调用runtime.deferproc时会将需要defer的表达式记录在表中,而在调用runtime.deferreturn的时候,则会依次从defer表中“出栈”并执行

如果有多个defer,调用顺序类似栈,越后面的defer表达式越先被调用

defer链

defer信息会注册到链表,当前执行的 goroutine 持有这个链表的头指针,每个 goroutine 都有一个对应的结构体struct G,其中有一个字段指向这个defer链表头

type g struct {
	// Stack parameters.
	// stack describes the actual stack memory: [stack.lo, stack.hi).
	// stackguard0 is the stack pointer compared in the Go stack growth prologue.
	// It is stack.lo+StackGuard normally, but can be StackPreempt to trigger a preemption.
	// stackguard1 is the stack pointer compared in the C stack growth prologue.
	// It is stack.lo+StackGuard on g0 and gsignal stacks.
	// It is ~0 on other goroutine stacks, to trigger a call to morestackc (and crash).
	stack       stack   // offset known to runtime/cgo
	stackguard0 uintptr // offset known to liblink
	stackguard1 uintptr // offset known to liblink

	_panic       *_panic // innermost panic - offset known to liblink
    // _defer 这个字段指向defer链表头
	_defer       *_defer // innermost defer
    ...
}

新注册的defer会添加到链表头,所以感觉像是栈那样先进后出的调用:

源码分析

deferproc一共有两个参数,第一个是参数和返回值的大小,第二个是指向funcval的指针

// Create a new deferred function fn with siz bytes of arguments.
// The compiler turns a defer statement into a call to this.
//go:nosplit
func deferproc(siz int32, fn *funcval) { // arguments of fn follow fn
    // 获取当前goroutine
	gp := getg()
	if gp.m.curg != gp {
		// go code on the system stack can't defer
		throw("defer on system stack")
	}
	// the arguments of fn are in a perilous state. The stack map
	// for deferproc does not describe them. So we can't let garbage
	// collection or stack copying trigger until we've copied them out
	// to somewhere safe. The memmove below does that.
	// Until the copy completes, we can only call nosplit routines.
    // 获取调用者指针
	sp := getcallersp()
    // 通过偏移获得参数
	argp := uintptr(unsafe.Pointer(&fn)) + unsafe.Sizeof(fn)
	callerpc := getcallerpc()

    // 创建defer结构体
	d := newdefer(siz)
	if d._panic != nil {
		throw("deferproc: d.panic != nil after newdefer")
	}
    // 初始化
	d.link = gp._defer
	gp._defer = d
	d.fn = fn
	d.pc = callerpc
	d.sp = sp
	switch siz {
	case 0:
		// Do nothing.
	case sys.PtrSize:
		*(*uintptr)(deferArgs(d)) = *(*uintptr)(unsafe.Pointer(argp))
	default:
		memmove(deferArgs(d), unsafe.Pointer(argp), uintptr(siz))
	}

	// deferproc returns 0 normally.
	// a deferred func that stops a panic
	// makes the deferproc return 1.
	// the code the compiler generates always
	// checks the return value and jumps to the
	// end of the function if deferproc returns != 0.
	return0()
	// No code can go here - the C return register has
	// been set and must not be clobbered.
}
// 以下是_defer结构体
// A _defer holds an entry on the list of deferred calls.
// If you add a field here, add code to clear it in freedefer and deferProcStack
// This struct must match the code in cmd/compile/internal/gc/reflect.go:deferstruct
// and cmd/compile/internal/gc/ssa.go:(*state).call.
// Some defers will be allocated on the stack and some on the heap.
// All defers are logically part of the stack, so write barriers to
// initialize them are not required. All defers must be manually scanned,
// and for heap defers, marked.
type _defer struct {
    // siz 记录defer的参数和返回值共占多少字节
    // 会直接分配在_defer后面,在注册时保存参数,在执行完成时拷贝到调用者参数和返回值空间
	siz     int32 // includes both arguments and results
	// started 标记是否已经执行
    started bool
    // heap go1.13优化,标识是否为堆分配
	heap    bool
	// openDefer indicates that this _defer is for a frame with open-coded
	// defers. We have only one defer record for the entire frame (which may
	// currently have 0, 1, or more defers active).
    // openDefer 是否是open defer,通过这些信息可以找到未注册到链表的defer函数
	openDefer bool
    // sp 记录调用者栈指针,可以通过它判断自己注册的defer是否已经执行完了
	sp        uintptr  // sp at time of defer
    // pc deferproc的返回地址
	pc        uintptr  // pc at time of defer
    // fn 要注册的funcval
	fn        *funcval // can be nil for open-coded defers
    // _panic 指向当前的panic,表示这个defer是由这个panic触发的
	_panic    *_panic  // panic that is running defer
    // link 链到前一个注册的defer结构体
	link      *_defer

	// If openDefer is true, the fields below record values about the stack
	// frame and associated function that has the open-coded defer(s). sp
	// above will be the sp for the frame, and pc will be address of the
	// deferreturn call in the function.
    // 通过这些信息可以找到未注册到链表的defer函数
	fd   unsafe.Pointer // funcdata for the function associated with the frame
	varp uintptr        // value of varp for the stack frame
	// framepc is the current pc associated with the stack frame. Together,
	// with sp above (which is the sp associated with the stack frame),
	// framepc/sp can be used as pc/sp pair to continue a stack trace via
	// gentraceback().
	framepc uintptr
}

defer将参数注册的时候拷贝到堆上,执行时再(将参数和返回值)拷贝回栈上

go会分配不同规格的_defer pool,执行时从空闲_defer中取一个出来用,没有合适的再进行堆分配。用完以后再放回空闲_defer pool。以避免频繁的堆分配和回收

优化

go1.12中defer存在的问题:

  • defer信息主要存储在堆上,要在堆和栈上来回拷贝返回值和参数很慢
  • defer结构体通过链表链起来,而链表的操作也很慢

go1.13中defer的优化:

  • 减少了defer信息的堆分配。再通过deferprocStack将整个defer注册到defer链表中
  • 将一般情况的defer信息存储在函数栈帧的局部变量区域
  • 显示循环或者是隐式循环的defer还是需要用到go1.12中defer信息的堆分配
  • 官方给出的性能提升是30%

go1.14中defer的优化:

  • 在编译阶段插入代码,把defer函数的执行逻辑展开在所属函数内,避免创建defer结构体,而且不需要注册到defer链表。称为 open coded defer
  • 与1.13一样不适用于循环中的defer
  • 性能几乎提升了一个数量级
  • open coded defer 中发生panic 或 调用runtime.Goexit(),后面未注册到的defer函数无法执行到,需要栈扫描。defer结构体中就多添加了一些字段,借助这些字段可以找到未注册到链表中的defer函数

结果就是defer变快了,但是panic变慢了

defer添加了局部变量去判断是否需要执行,需要执行的话就将标识df对应的位上或一下,如果是有条件的defer,需要根据具体条件去或df

deferprocStack

// deferprocStack queues a new deferred function with a defer record on the stack.
// The defer record must have its siz and fn fields initialized.
// All other fields can contain junk.
// The defer record must be immediately followed in memory by
// the arguments of the defer.
// Nosplit because the arguments on the stack won't be scanned
// until the defer record is spliced into the gp._defer list.
//go:nosplit
func deferprocStack(d *_defer) {
    // 获得当前 goroutine
	gp := getg()
	if gp.m.curg != gp {
		// go code on the system stack can't defer
		throw("defer on system stack")
	}
	// siz and fn are already set.
	// The other fields are junk on entry to deferprocStack and
	// are initialized here.
    // 初始化 _defer 信息
	d.started = false
	d.heap = false
	d.openDefer = false
	d.sp = getcallersp()
	d.pc = getcallerpc()
	d.framepc = 0
	d.varp = 0
	// The lines below implement:
	//   d.panic = nil
	//   d.fd = nil
	//   d.link = gp._defer
	//   gp._defer = d
	// But without write barriers. The first three are writes to
	// the stack so they don't need a write barrier, and furthermore
	// are to uninitialized memory, so they must not use a write barrier.
	// The fourth write does not require a write barrier because we
	// explicitly mark all the defer structures, so we don't need to
	// keep track of pointers to them with a write barrier.
	*(*uintptr)(unsafe.Pointer(&d._panic)) = 0
	*(*uintptr)(unsafe.Pointer(&d.fd)) = 0
	*(*uintptr)(unsafe.Pointer(&d.link)) = uintptr(unsafe.Pointer(gp._defer))
	*(*uintptr)(unsafe.Pointer(&gp._defer)) = uintptr(unsafe.Pointer(d))

	return0()
	// No code can go here - the C return register has
	// been set and must not be clobbered.
}

到此这篇关于Golang的关键字defer的使用的文章就介绍到这了,更多相关 Golang关键字defer内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 聊聊golang中多个defer的执行顺序

    golang 中多个 defer 的执行顺序 引用 Ture Go 中的一个示例: package main import "fmt" func main() { fmt.Println("counting") for i := 0; i < 10; i++ { defer fmt.Println(i) } fmt.Println("done") } 程序执行结果为: counting done 9 8 7 6 5 4 3 2 1 0 从结

  • golang中defer的关键特性示例详解

    前言 大家都知道golang的defer关键字,它可以在函数返回前执行一些操作,最常用的就是打开一个资源(例如一个文件.数据库连接等)时就用defer延迟关闭改资源,以免引起内存泄漏.本文主要给大家介绍了关于golang中defer的关键特性,分享出来供大家参考学习,下面话不多说,来一起看看详细的介绍: 一.defer 的作用和执行时机 go 的 defer 语句是用来延迟执行函数的,而且延迟发生在调用函数 return 之后,比如 func a() int { defer b() return

  • 简单聊聊Golang中defer预计算参数

    目录 什么是defer Go语言defer预计算参数 总结 什么是defer defer用来声明一个延迟函数,把这个函数放入到一个栈上, 当外部的包含方法return之前,返回参数到调用方法之前调用,也可以说是运行到最外层方法体的"}"时调用.我们经常用他来做一些资源的释放,比如关闭io操作 func doSomething(fileName string) { file,err := os.Open(fileName) if err != nil { panic(err) } def

  • Golang 的defer执行规则说明

    defer介绍 defer是golang的一个特色功能,被称为"延迟调用函数".当外部函数返回后执行defer.类似于其他语言的 try- catch - finally- 中的finally,当然差别还是明显的. 在使用defer之前我们应该多了解defer的特性,这样才能避免使用上的误区. 1. 最简单的defer func test(){ defer func(){ fmt.Println("defer") }() //todo //... return //

  • Golang学习笔记之延迟函数(defer)的使用小结

    golang的defer优雅又简洁, 是golang的亮点之一.defer在声明时不会立即执行,而是在函数return后,再按照先进后出的原则依次执行每个defer,一般用于释放资源.清理数据.记录日志.异常处理等. 关键字defer于注册延迟调用.这些调用直到 ret 前才被执行,通常用于释放资源或错误处理. 一.当defer被声明时,其参数就会被实时解析 func a() { i := 0 defer fmt.Println(i) //输出0,因为i此时就是0 i++ defer fmt.P

  • golang中defer的使用规则详解

    前言 在golang当中,defer代码块会在函数调用链表中增加一个函数调用.这个函数调用不是普通的函数调用,而是会在函数正常返回,也就是return之后添加一个函数调用.因此,defer通常用来释放函数内部变量. 为了更好的学习defer的行为,我们首先来看下面一段代码: func CopyFile(dstName, srcName string) (written int64, err error) { src, err := os.Open(srcName) if err != nil {

  • Golang巧用defer进行错误处理的方法

    本文主要跟大家介绍了Golang巧用defer进行错误处理的相关内容,分享出来供大家参考学习,下面来看看详细的介绍: 问题引入 毫无疑问,错误处理是程序的重要组成部分,有效且优雅的处理错误是大多数程序员的追求.很多程序员都有C/C++的编程背景,Golang的程序员也不例外,他们处理错误有意无意的带着C/C++的烙印. 我们看看下面的例子,就有一种似曾相识的赶脚,代码如下: func deferDemo() error { err := createResource1() if err != n

  • 聊聊golang的defer的使用

    序 本文主要研究一下golang的defer defer return先赋值(对于命名返回值),然后执行defer,最后函数返回 defer函数调用的执行顺序与它们分别所属的defer语句的执行顺序相反 defer后面的表达式可以是func或者是method的调用,如果defer的函数为nil,则会panic 实例 实例1 // f returns 42 func f() (result int) { defer func() { // result is accessed after it w

  • Golang之defer 延迟调用操作

    前言 defer语句被用于预定对一个函数的调用.我们把这类被defer语句调用的函数称为延迟函数.而defer 延迟语句在其他编程语言里好像没有见到.应该是属于 Go 语言里的独有的关键字.但用法类似于面向对象编程语言 Java 和 C# 的 finally 语句块. 下面对defer进行介绍. defer特性 1. 关键字 defer 用于注册延迟调用. 2. 这些调用直到 return 前才被执.因此,可以用来做资源清理. 3. 多个defer语句,按先进后出的方式执行. 1.延迟调用 用法

  • Golang异常处理之defer,panic,recover的使用详解

    目录 延迟是什么 延迟函数 延迟⽅法 延迟参数 堆栈的推迟 延迟的应⽤ panic和recover(宕机和宕机恢复) panic和recover机制 示例代码 延迟是什么 defer即延迟语句,极个别的情况下,Go才使⽤defer.panic.recover这种异常处理形式. defer可以延迟函数.延迟⽅法.延迟参数. 延迟函数 可以在函数中添加多个defer语句. 当函数执⾏到最后时,这些defer语句会按照逆序执⾏,最后该函数返回.特别是当你在进⾏⼀些打开资源的操作时,遇到错误需要提前返回

随机推荐