【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

相关文章

C++统计函数执行时间的最佳实践

《C++统计函数执行时间的最佳实践》在软件开发过程中,性能分析是优化程序的重要环节,了解函数的执行时间分布对于识别性能瓶颈至关重要,本文将分享一个C++函数执行时间统计工具,希望对大家有所帮助... 目录前言工具特性核心设计1. 数据结构设计2. 单例模式管理器3. RAII自动计时使用方法基本用法高级用法

Java实现远程执行Shell指令

《Java实现远程执行Shell指令》文章介绍使用JSch在SpringBoot项目中实现远程Shell操作,涵盖环境配置、依赖引入及工具类编写,详解分号和双与号执行多指令的区别... 目录软硬件环境说明编写执行Shell指令的工具类总结jsch(Java Secure Channel)是SSH2的一个纯J

Python 基于http.server模块实现简单http服务的代码举例

《Python基于http.server模块实现简单http服务的代码举例》Pythonhttp.server模块通过继承BaseHTTPRequestHandler处理HTTP请求,使用Threa... 目录测试环境代码实现相关介绍模块简介类及相关函数简介参考链接测试环境win11专业版python

GO语言短变量声明的实现示例

《GO语言短变量声明的实现示例》在Go语言中,短变量声明是一种简洁的变量声明方式,使用:=运算符,可以自动推断变量类型,下面就来具体介绍一下如何使用,感兴趣的可以了解一下... 目录基本语法功能特点与var的区别适用场景注意事项基本语法variableName := value功能特点1、自动类型推

GO语言中函数命名返回值的使用

《GO语言中函数命名返回值的使用》在Go语言中,函数可以为其返回值指定名称,这被称为命名返回值或命名返回参数,这种特性可以使代码更清晰,特别是在返回多个值时,感兴趣的可以了解一下... 目录基本语法函数命名返回特点代码示例命名特点基本语法func functionName(parameters) (nam

python 线程池顺序执行的方法实现

《python线程池顺序执行的方法实现》在Python中,线程池默认是并发执行任务的,但若需要实现任务的顺序执行,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋... 目录方案一:强制单线程(伪顺序执行)方案二:按提交顺序获取结果方案三:任务间依赖控制方案四:队列顺序消

Go之errors.New和fmt.Errorf 的区别小结

《Go之errors.New和fmt.Errorf的区别小结》本文主要介绍了Go之errors.New和fmt.Errorf的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考... 目录error的基本用法1. 获取错误信息2. 在条件判断中使用基本区别1.函数签名2.使用场景详细对

Unity新手入门学习殿堂级知识详细讲解(图文)

《Unity新手入门学习殿堂级知识详细讲解(图文)》Unity是一款跨平台游戏引擎,支持2D/3D及VR/AR开发,核心功能模块包括图形、音频、物理等,通过可视化编辑器与脚本扩展实现开发,项目结构含A... 目录入门概述什么是 UnityUnity引擎基础认知编辑器核心操作Unity 编辑器项目模式分类工程

Go语言连接MySQL数据库执行基本的增删改查

《Go语言连接MySQL数据库执行基本的增删改查》在后端开发中,MySQL是最常用的关系型数据库之一,本文主要为大家详细介绍了如何使用Go连接MySQL数据库并执行基本的增删改查吧... 目录Go语言连接mysql数据库准备工作安装 MySQL 驱动代码实现运行结果注意事项Go语言执行基本的增删改查准备工作

Go中select多路复用的实现示例

《Go中select多路复用的实现示例》Go的select用于多通道通信,实现多路复用,支持随机选择、超时控制及非阻塞操作,建议合理使用以避免协程泄漏和死循环,感兴趣的可以了解一下... 目录一、什么是select基本语法:二、select 使用示例示例1:监听多个通道输入三、select的特性四、使用se