【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

相关文章

全面解析Golang 中的 Gorilla CORS 中间件正确用法

《全面解析Golang中的GorillaCORS中间件正确用法》Golang中使用gorilla/mux路由器配合rs/cors中间件库可以优雅地解决这个问题,然而,很多人刚开始使用时会遇到配... 目录如何让 golang 中的 Gorilla CORS 中间件正确工作一、基础依赖二、错误用法(很多人一开

解密SQL查询语句执行的过程

《解密SQL查询语句执行的过程》文章讲解了SQL语句的执行流程,涵盖解析、优化、执行三个核心阶段,并介绍执行计划查看方法EXPLAIN,同时提出性能优化技巧如合理使用索引、避免SELECT*、JOIN... 目录1. SQL语句的基本结构2. SQL语句的执行过程3. SQL语句的执行计划4. 常见的性能优

go动态限制并发数量的实现示例

《go动态限制并发数量的实现示例》本文主要介绍了Go并发控制方法,通过带缓冲通道和第三方库实现并发数量限制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录带有缓冲大小的通道使用第三方库其他控制并发的方法因为go从语言层面支持并发,所以面试百分百会问到

Go语言并发之通知退出机制的实现

《Go语言并发之通知退出机制的实现》本文主要介绍了Go语言并发之通知退出机制的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1、通知退出机制1.1 进程/main函数退出1.2 通过channel退出1.3 通过cont

Spring Bean初始化及@PostConstruc执行顺序示例详解

《SpringBean初始化及@PostConstruc执行顺序示例详解》本文给大家介绍SpringBean初始化及@PostConstruc执行顺序,本文通过实例代码给大家介绍的非常详细,对大家的... 目录1. Bean初始化执行顺序2. 成员变量初始化顺序2.1 普通Java类(非Spring环境)(

Spring Boot 中的默认异常处理机制及执行流程

《SpringBoot中的默认异常处理机制及执行流程》SpringBoot内置BasicErrorController,自动处理异常并生成HTML/JSON响应,支持自定义错误路径、配置及扩展,如... 目录Spring Boot 异常处理机制详解默认错误页面功能自动异常转换机制错误属性配置选项默认错误处理

如何在Java Spring实现异步执行(详细篇)

《如何在JavaSpring实现异步执行(详细篇)》Spring框架通过@Async、Executor等实现异步执行,提升系统性能与响应速度,支持自定义线程池管理并发,本文给大家介绍如何在Sprin... 目录前言1. 使用 @Async 实现异步执行1.1 启用异步执行支持1.2 创建异步方法1.3 调用

Go语言编译环境设置教程

《Go语言编译环境设置教程》Go语言支持高并发(goroutine)、自动垃圾回收,编译为跨平台二进制文件,云原生兼容且社区活跃,开发便捷,内置测试与vet工具辅助检测错误,依赖模块化管理,提升开发效... 目录Go语言优势下载 Go  配置编译环境配置 GOPROXYIDE 设置(VS Code)一些基本

Java中使用 @Builder 注解的简单示例

《Java中使用@Builder注解的简单示例》@Builder简化构建但存在复杂性,需配合其他注解,导致可变性、抽象类型处理难题,链式编程非最佳实践,适合长期对象,避免与@Data混用,改用@G... 目录一、案例二、不足之处大多数同学使用 @Builder 无非就是为了链式编程,然而 @Builder

使用Go实现文件复制的完整流程

《使用Go实现文件复制的完整流程》本案例将实现一个实用的文件操作工具:将一个文件的内容完整复制到另一个文件中,这是文件处理中的常见任务,比如配置文件备份、日志迁移、用户上传文件转存等,文中通过代码示例... 目录案例说明涉及China编程知识点示例代码代码解析示例运行练习扩展小结案例说明我们将通过标准库 os