【Go学习】一道简单Golang面试题中关于panic和defer的执行顺序引发的惨案

本文主要是介绍【Go学习】一道简单Golang面试题中关于panic和defer的执行顺序引发的惨案,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

【Go学习】一道简单Golang面试题中关于panic和defer的执行顺序引发的惨案

题目有点夸张,标题党一把,哈哈,不过也确实是在一个小的面试中碰到这个题目,然后当时经过我反复斟酌之后,愉快的写下了一个错误的答案,回来之后,自己验证了一下,于是就有了这篇文章,大神请绕道。
废话不多说直接上题目,说有如下程序(main.go),写出运行之后的结果:

package mainimport "fmt"func main(){defer_call()fmt.Println("333 Helloworld")
}func defer_call()  {defer func(){fmt.Println("11111")}()defer func(){fmt.Println("22222")}()defer func() {if r := recover(); r!= nil {fmt.Println("Recover from r : ",r)}}()defer func(){fmt.Println("33333")}()fmt.Println("111 Helloworld")panic("Panic 1!")panic("Panic 2!")fmt.Println("222 Helloworld")
}

我直接贴出运行结果:

111 Helloworld
33333
Recover from r :  Panic 1!
22222
11111
333 Helloworld

如果你做对了,建议跳过。其实我也只是把自己的验证过程记录如下,以便以后查阅。

我们用上一篇文章所搭建的golang的gdb调试环境来具体分析下为什么会是这个结果。

编译源代码使用以下命令, 这里的-l参数的意思和上面一样, 如果有需要还可以加-N参数:

/home/james/workspace/go_src/bin/go build -gcflags "-l" main.go

对这个编译方法有疑问的可以参考上一篇文章。
编译后使用gdb运行:
这里写图片描述
go里面的函数符号名称的命名规则是包名称.函数名称, 例如主函数的符号名称是main.main, 运行时中的newobject的符号名称是runtime.newobject.
首先给主函数下一个断点,给我们第一个panic("Panic 1!")所在行下一个断点,然后运行:
这里写图片描述
单步运行之后,我们可以找到panic函数所对应的源码:
这里写图片描述

在上一篇文章中所准备的源码中找到对应的文件src/rumtime/panic.go:425,即panic函数具体实现如下:

// The implementation of the predeclared function panic.
func gopanic(e interface{}) {gp := getg()    // getg()返回当前协程的 g 结构体指针,g 结构体描述 goroutineif gp.m.curg != gp {print("panic: ")printany(e)print("\n")throw("panic on system stack")}// m.softfloat is set during software floating point.// It increments m.locks to avoid preemption.// We moved the memory loads out, so there shouldn't be// any reason for it to panic anymore.if gp.m.softfloat != 0 {gp.m.locks--gp.m.softfloat = 0throw("panic during softfloat")}if gp.m.mallocing != 0 {print("panic: ")printany(e)print("\n")throw("panic during malloc")}if gp.m.preemptoff != "" {print("panic: ")printany(e)print("\n")print("preempt off reason: ")print(gp.m.preemptoff)print("\n")throw("panic during preemptoff")}if gp.m.locks != 0 {print("panic: ")printany(e)print("\n")throw("panic holding locks")}var p _panicp.arg = ep.link = gp._panicgp._panic = (*_panic)(noescape(unsafe.Pointer(&p)))atomic.Xadd(&runningPanicDefers, 1)for {d := gp._defer    // 获取当前协程defer链表的头节点if d == nil {break    // 当前协程的defer都被执行后,defer链表为空,此时退出for循环}// If defer was started by earlier panic or Goexit (and, since we're back here, that triggered a new panic),// take defer off list. The earlier panic or Goexit will not continue running.if d.started {    // 发生panic后,在defer中又遇到panic(),则会进入这个代码块if d._panic != nil {d._panic.aborted = true}d._panic = nild.fn = nilgp._defer = d.linkfreedefer(d)  // defer 已经被执行过,则释放这个defer,继续for循环。continue}// Mark defer as started, but keep on list, so that traceback// can find and update the defer's argument frame if stack growth// or a garbage collection happens before reflectcall starts executing d.fn.d.started = true// Record the panic that is running the defer.// If there is a new panic during the deferred call, that panic// will find d in the list and will mark d._panic (this panic) aborted.d._panic = (*_panic)(noescape(unsafe.Pointer(&p)))p.argp = unsafe.Pointer(getargp(0))reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))   // 执行当前协程defer链表头的deferp.argp = nil// reflectcall did not panic. Remove d.if gp._defer != d {throw("bad defer entry in panic")}d._panic = nild.fn = nilgp._defer = d.link  // 从defer链中移除刚刚执行过的defer// trigger shrinkage to test stack copy. See stack_test.go:TestStackPanic//GC()pc := d.pcsp := unsafe.Pointer(d.sp) // must be pointer so it gets adjusted during stack copyfreedefer(d)   // 释放刚刚执行过的deferif p.recovered {    // defer()中遇到recover后进入这个代码块atomic.Xadd(&runningPanicDefers, -1)gp._panic = p.link// Aborted panics are marked but remain on the g.panic list.// Remove them from the list.for gp._panic != nil && gp._panic.aborted {gp._panic = gp._panic.link}if gp._panic == nil { // must be done with signalgp.sig = 0}// Pass information about recovering frame to recovery.gp.sigcode0 = uintptr(sp)gp.sigcode1 = pcmcall(recovery)   // 跳转到recover()处,继续往下执行throw("recovery failed") // mcall should not return}}// ran out of deferred calls - old-school panic now// Because it is unsafe to call arbitrary user code after freezing// the world, we call preprintpanics to invoke all necessary Error// and String methods to prepare the panic strings before startpanic.preprintpanics(gp._panic)startpanic()// startpanic set panicking, which will block main from exiting,// so now OK to decrement runningPanicDefers.atomic.Xadd(&runningPanicDefers, -1)printpanics(gp._panic)   // 输出panic信息dopanic(0)       // should not return*(*int)(nil) = 0 // not reached
}

上面代码虽然有些没有看懂,但是其执行流程还是比较清楚,从代码上来看,协程遇到panic时,遍历本协程的defer链表,并执行defer。在执行defer过程中,遇到recover则停止panic,返回recover处继续往下执行。如果没有遇到recover,遍历完本协程的defer链表后,向stderr抛出panic信息。从执行顺序上来看,实际上是按照先进后出的顺序执行defer。这个时候应该会理解上面的面试题答案为什么是那样了。

这篇关于【Go学习】一道简单Golang面试题中关于panic和defer的执行顺序引发的惨案的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/318571

相关文章

Java8需要知道的4个函数式接口简单教程

《Java8需要知道的4个函数式接口简单教程》:本文主要介绍Java8中引入的函数式接口,包括Consumer、Supplier、Predicate和Function,以及它们的用法和特点,文中... 目录什么是函数是接口?Consumer接口定义核心特点注意事项常见用法1.基本用法2.结合andThen链

Golang基于内存的键值存储缓存库go-cache

《Golang基于内存的键值存储缓存库go-cache》go-cache是一个内存中的key:valuestore/cache库,适用于单机应用程序,本文主要介绍了Golang基于内存的键值存储缓存库... 目录文档安装方法示例1示例2使用注意点优点缺点go-cache 和 Redis 缓存对比1)功能特性

Golang中map缩容的实现

《Golang中map缩容的实现》本文主要介绍了Go语言中map的扩缩容机制,包括grow和hashGrow方法的处理,具有一定的参考价值,感兴趣的可以了解一下... 目录基本分析带来的隐患为什么不支持缩容基本分析在 Go 底层源码 src/runtime/map.go 中,扩缩容的处理方法是 grow

Go 1.23中Timer无buffer的实现方式详解

《Go1.23中Timer无buffer的实现方式详解》在Go1.23中,Timer的实现通常是通过time包提供的time.Timer类型来实现的,本文主要介绍了Go1.23中Timer无buff... 目录Timer 的基本实现无缓冲区的实现自定义无缓冲 Timer 实现更复杂的 Timer 实现总结在

Go使用pprof进行CPU,内存和阻塞情况分析

《Go使用pprof进行CPU,内存和阻塞情况分析》Go语言提供了强大的pprof工具,用于分析CPU、内存、Goroutine阻塞等性能问题,帮助开发者优化程序,提高运行效率,下面我们就来深入了解下... 目录1. pprof 介绍2. 快速上手:启用 pprof3. CPU Profiling:分析 C

grom设置全局日志实现执行并打印sql语句

《grom设置全局日志实现执行并打印sql语句》本文主要介绍了grom设置全局日志实现执行并打印sql语句,包括设置日志级别、实现自定义Logger接口以及如何使用GORM的默认logger,通过这些... 目录gorm中的自定义日志gorm中日志的其他操作日志级别Debug自定义 Loggergorm中的

golang获取prometheus数据(prometheus/client_golang包)

《golang获取prometheus数据(prometheus/client_golang包)》本文主要介绍了使用Go语言的prometheus/client_golang包来获取Prometheu... 目录1. 创建链接1.1 语法1.2 完整示例2. 简单查询2.1 语法2.2 完整示例3. 范围值

golang panic 函数用法示例详解

《golangpanic函数用法示例详解》在Go语言中,panic用于触发不可恢复的错误,终止函数执行并逐层向上触发defer,最终若未被recover捕获,程序会崩溃,recover用于在def... 目录1. panic 的作用2. 基本用法3. recover 的使用规则4. 错误处理建议5. 常见错

golang字符串匹配算法解读

《golang字符串匹配算法解读》文章介绍了字符串匹配算法的原理,特别是Knuth-Morris-Pratt(KMP)算法,该算法通过构建模式串的前缀表来减少匹配时的不必要的字符比较,从而提高效率,在... 目录简介KMP实现代码总结简介字符串匹配算法主要用于在一个较长的文本串中查找一个较短的字符串(称为

使用Go语言开发一个命令行文件管理工具

《使用Go语言开发一个命令行文件管理工具》这篇文章主要为大家详细介绍了如何使用Go语言开发一款命令行文件管理工具,支持批量重命名,删除,创建,移动文件,需要的小伙伴可以了解下... 目录一、工具功能一览二、核心代码解析1. 主程序结构2. 批量重命名3. 批量删除4. 创建文件/目录5. 批量移动三、如何安