go 關(guān)于defer在何時(shí)執(zhí)行的思考


一段簡(jiǎn)單的程序

package main

func main() {
    f1()
}

func f1() (result int) {
    defer func() {
        result = result + 1
    }()
    return 12
}
// Output:
// 13

來(lái)看看匯編

(gdb) disas
Dump of assembler code for function main.f1:
   0x000000000044ebe0 <+0>:     mov    rcx,QWORD PTR fs:0xfffffffffffffff8
   0x000000000044ebe9 <+9>:     cmp    rsp,QWORD PTR [rcx+0x10]
   0x000000000044ebed <+13>:    jbe    0x44ec55 <main.f1+117>
   0x000000000044ebef <+15>:    sub    rsp,0x20
   0x000000000044ebf3 <+19>:    mov    QWORD PTR [rsp+0x18],rbp
   0x000000000044ebf8 <+24>:    lea    rbp,[rsp+0x18]
   0x000000000044ebfd <+29>:    mov    QWORD PTR [rsp+0x28],0x0
   0x000000000044ec06 <+38>:    lea    rax,[rsp+0x28]
   0x000000000044ec0b <+43>:    mov    QWORD PTR [rsp+0x10],rax
   0x000000000044ec10 <+48>:    mov    DWORD PTR [rsp],0x8
   0x000000000044ec17 <+55>:    lea    rax,[rip+0x21d92]        # 0x4709b0
   0x000000000044ec1e <+62>:    mov    QWORD PTR [rsp+0x8],rax
   0x000000000044ec23 <+67>:    call   0x420f70 <runtime.deferproc>
   0x000000000044ec28 <+72>:    test   eax,eax
   0x000000000044ec2a <+74>:    jne    0x44ec45 <main.f1+101>
=> 0x000000000044ec2c <+76>:    mov    QWORD PTR [rsp+0x28],0xc
   0x000000000044ec35 <+85>:    nop
   0x000000000044ec36 <+86>:    call   0x4217f0 <runtime.deferreturn>
   0x000000000044ec3b <+91>:    mov    rbp,QWORD PTR [rsp+0x18]
   0x000000000044ec40 <+96>:    add    rsp,0x20
   0x000000000044ec44 <+100>:   ret
   0x000000000044ec45 <+101>:   nop
   0x000000000044ec46 <+102>:   call   0x4217f0 <runtime.deferreturn>
   0x000000000044ec4b <+107>:   mov    rbp,QWORD PTR [rsp+0x18]
   0x000000000044ec50 <+112>:   add    rsp,0x20
   0x000000000044ec54 <+116>:   ret
   0x000000000044ec55 <+117>:   call   0x446f20 <runtime.morestack_noctxt>
   0x000000000044ec5a <+122>:   jmp    0x44ebe0 <main.f1>
可以看出,系統(tǒng)先執(zhí)行了deferproc然后給result賦值12再去執(zhí)行了deferreturn。
如果說(shuō)defer內(nèi)的閉包是在deferproc內(nèi)執(zhí)行的話,這里的賦值操作會(huì)將result直接賦值,
不管閉包內(nèi)對(duì)其做的任何操作,輸出的結(jié)果應(yīng)該為12。

來(lái)看看deferproc都做了什么

func deferproc(siz int32, fn *funcval) { // arguments of fn follow fn
    if getg().m.curg != getg() {
        // 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()

    d := newdefer(siz)
    if d._panic != nil {
        throw("deferproc: d.panic != nil after newdefer")
    }
    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.
}
在這里并沒(méi)有做閉包的調(diào)用

再看看deferreturn

func deferreturn(arg0 uintptr) {
    gp := getg()
    d := gp._defer
    if d == nil {
        return
    }
    sp := getcallersp()
    if d.sp != sp {
        return
    }

    // Moving arguments around.
    //
    // Everything called after this point must be recursively
    // nosplit because the garbage collector won't know the form
    // of the arguments until the jmpdefer can flip the PC over to
    // fn.
    switch d.siz {
    case 0:
        // Do nothing.
    case sys.PtrSize:
        *(*uintptr)(unsafe.Pointer(&arg0)) = *(*uintptr)(deferArgs(d))
    default:
        memmove(unsafe.Pointer(&arg0), deferArgs(d), uintptr(d.siz))
    }
    fn := d.fn
    d.fn = nil
    gp._defer = d.link
    freedefer(d)
    jmpdefer(fn, uintptr(unsafe.Pointer(&arg0)))
}
// asm_amd64.s

// void jmpdefer(fn, sp);
// called from deferreturn.
// 1. pop the caller
// 2. sub 5 bytes from the callers return
// 3. jmp to the argument
TEXT runtime·jmpdefer(SB), NOSPLIT, $0-16
    MOVQ    fv+0(FP), DX    // fn
    MOVQ    argp+8(FP), BX  // caller sp
    LEAQ    -8(BX), SP  // caller sp after CALL
    MOVQ    -8(SP), BP  // restore BP as if deferreturn returned (harmless if framepointers not in use)
    SUBQ    $5, (SP)    // return to CALL again
    MOVQ    0(DX), BX
    JMP BX  // but first run the deferred function
在這里才是閉包的真正調(diào)用

總結(jié)

之前一直信奉別人所說(shuō)的defer執(zhí)行是在作用域返回前,以為一定會(huì)在return之前執(zhí)行,
經(jīng)過(guò)自己的深入才發(fā)現(xiàn)執(zhí)行的真正順序。執(zhí)行的順序一定要去分析才能了解,
下次再去分析一下panic和defer的調(diào)用順序。

有什么不對(duì)的地方歡迎指出

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 昨天看了貓叔公眾號(hào)的文章,提了一個(gè)有趣的問(wèn)題讓人填空, 即兩名A罩杯的女大學(xué)生,一個(gè)一心學(xué)習(xí)、考研,對(duì)胸部...
    十米白色閱讀 701評(píng)論 0 0
  • 獲取URL 通過(guò)$_SERVER['REQUEST_URI']來(lái)獲取請(qǐng)求路徑 index.php隱藏 apache...
    ozil_oo閱讀 645評(píng)論 0 0
  • API: 法官同意\不同意邀請(qǐng) URL: /update_invite/ 請(qǐng)求方式: POST 參數(shù) 返回示例 ...
    一曲廣陵散閱讀 268評(píng)論 0 0
  • 七年級(jí),一個(gè)懵懂而又單純的年紀(jì)。并對(duì)愛(ài)情這件事有著更多的期待和幻想,于我而言,也遇到了這樣令我怦然心動(dòng)的那個(gè)...
    唐麗瑩閱讀 644評(píng)論 0 1
  • 近來(lái)的工作,很壓抑,不明白自己為什么會(huì)這樣。尤其這節(jié)科學(xué)公開(kāi)課給自己帶來(lái)的沖擊,也承認(rèn)自己的些許不足,可是越來(lái)越遞...
    葡萄活在未來(lái)閱讀 341評(píng)論 0 1

友情鏈接更多精彩內(nèi)容