首頁  >  文章  >  後端開發  >  Golang Defer:堆疊分配、堆疊分配、開放式編碼的 Defer

Golang Defer:堆疊分配、堆疊分配、開放式編碼的 Defer

WBOY
WBOY原創
2024-08-07 18:10:56268瀏覽

這是帖子的摘錄;完整的帖子可以在這裡找到:Golang Defer:從基礎到陷阱。

defer 語句可能是我們開始學習 Go 時首先發現非常有趣的事情之一,對吧?

但是它還有很多讓很多人困惑的地方,並且有許多令人著迷的方面是我們在使用它時經常沒有觸及的。

Golang Defer: Heap-allocated, Stack-allocated, Open-coded Defer

堆疊分配、堆疊分配、開放式編碼延遲

例如,defer 語句實際上有 3 種類型(從 Go 1.22 開始,儘管以後可能會改變):開放編碼 defer、堆疊分配 defer 和堆疊分配。每一種都有不同的效能和不同的最佳使用場景,如果您想優化效能,了解這一點很有幫助。

在本次討論中,我們將涵蓋從基礎知識到更高級用法的所有內容,我們甚至會深入研究一些內部細節。

什麼是延期?

在我們深入探討之前,讓我們先快速瀏覽一下 defer。

在 Go 中,defer 是一個關鍵字,用於延遲函數的執行,直到周圍的函數完成。

func main() {
  defer fmt.Println("hello")
  fmt.Println("world")
}

// Output:
// world
// hello

在此程式碼片段中,defer 語句安排 fmt.Println("hello") 在 main 函數的最後執行。因此,立即呼叫 fmt.Println("world"),並先列印「world」。之後,因為我們使用了 defer,所以在 main 完成之前的最後一步會列印「hello」。

這就像設定一個任務稍後運行,就在函數退出之前。這對於清理作業非常有用,例如關閉資料庫連線、釋放互斥體或關閉檔案:

func doSomething() error {
  f, err := os.Open("phuong-secrets.txt")
  if err != nil {
    return err
  }
  defer f.Close()

  // ...
}

上面的程式碼是展示 defer 如何運作的一個很好的例子,但這也是一個糟糕的使用 defer 的方式。我們將在下一節中討論這個問題。

「好吧,很好,但為什麼不把 f.Close() 放在最後呢?」

這樣做有幾個很好的理由:

  • 我們將關閉操作放在開啟附近,這樣更容易遵循邏輯並避免忘記關閉文件。我不想向下滾動函數來檢查文件是否已關閉;它分散了我對主要邏輯的注意力。
  • 即使發生恐慌(運行時錯誤),延遲函數也會在函數返回時被呼叫。

當發生恐慌時,堆疊將被展開,並且延遲函數將按特定順序執行,我們將在下一節中介紹。

延遲堆積

當您在函數中使用多個 defer 語句時,它們會按「堆疊」順序執行,這表示最後一個延遲函數會先執行。

func main() {
  defer fmt.Println(1)
  defer fmt.Println(2)
  defer fmt.Println(3)
}

// Output:
// 3
// 2
// 1

每次呼叫 defer 語句時,都會將此函數加入到目前 goroutine 鍊錶的頂部,如下所示:

Golang Defer: Heap-allocated, Stack-allocated, Open-coded Defer

Goroutine 延遲鏈

當函數傳回時,它會遍歷鍊錶並按照上圖所示的順序執行每個鍊錶。

但請記住,它不會執行 goroutine 鍊錶中的所有 defer,它只運行返回函數中的 defer,因為我們的 defer 鍊錶可能包含來自許多不同函數的許多 defer。

func B() {
  defer fmt.Println(1)
  defer fmt.Println(2)
  A()
}

func A() {
  defer fmt.Println(3)
  defer fmt.Println(4)
}

因此,僅執行目前函數(或目前堆疊幀)中的延遲函數。

Golang Defer: Heap-allocated, Stack-allocated, Open-coded Defer

Goroutine 延遲鏈

但是有一個典型情況,當前 goroutine 中的所有延遲函數都被追蹤並執行,那就是發生恐慌的時候。

延遲、恐慌和恢復

除了編譯時錯誤之外,我們還有很多執行時間錯誤:除以零(僅限整數)、越界、取消引用 nil 指標等等。這些錯誤會導致應用程式出現恐慌。

Panic 是一種停止當前 goroutine 執行、展開堆疊並執行當前 goroutine 中的延遲函數的方法,從而導致我們的應用程式崩潰。

為了處理意外錯誤並防止應用程式崩潰,您可以在延遲函數中使用復原函數來重新獲得對恐慌 goroutine 的控制。

func main() {
  defer func() {
    if r := recover(); r != nil {
      fmt.Println("Recovered:", r)
    }
  }()

  panic("This is a panic")
}

// Output:
// Recovered: This is a panic

通常,人們在恐慌中放入錯誤並使用recover(..)捕獲該錯誤,但它可以是任何東西:字串、整數等。

In the example above, inside the deferred function is the only place you can use recover. Let me explain this a bit more.

There are a couple of mistakes we could list here. I’ve seen at least three snippets like this in real code.

The first one is, using recover directly as a deferred function:

func main() {
  defer recover()

  panic("This is a panic")
}

The code above still panics, and this is by design of the Go runtime.

The recover function is meant to catch a panic, but it has to be called within a deferred function to work properly.

Behind the scenes, our call to recover is actually the runtime.gorecover, and it checks that the recover call is happening in the right context, specifically from the correct deferred function that was active when the panic occurred.

"Does that mean we can’t use recover in a function inside a deferred function, like this?"

func myRecover() {
  if r := recover(); r != nil {
    fmt.Println("Recovered:", r)
  }
}

func main() {
  defer func() {
    myRecover()
    // ...
  }()

  panic("This is a panic")
}

Exactly, the code above won’t work as you might expect. That’s because recover isn’t called directly from a deferred function but from a nested function.

Now, another mistake is trying to catch a panic from a different goroutine:

func main() {
  defer func() {
    if r := recover(); r != nil {
      fmt.Println("Recovered:", r)
    }
  }()

  go panic("This is a panic")

  time.Sleep(1 * time.Second) // Wait for the goroutine to finish
}

Makes sense, right? We already know that defer chains belong to a specific goroutine. It would be tough if one goroutine could intervene in another to handle the panic since each goroutine has its own stack.

Unfortunately, the only way out in this case is crashing the application if we don’t handle the panic in that goroutine.

Defer arguments, including receiver are immediately evaluated

I've run into this problem before, where old data got pushed to the analytics system, and it was tough to figure out why.

Here’s what I mean:

func pushAnalytic(a int) {
  fmt.Println(a)
}

func main() {
  a := 10
  defer pushAnalytic(a)

  a = 20
}

What do you think the output will be? It's 10, not 20.

That's because when you use the defer statement, it grabs the values right then. This is called "capture by value." So, the value of a that gets sent to pushAnalytic is set to 10 when the defer is scheduled, even though a changes later.

There are two ways to fix this.

...

Full post is available here: Golang Defer: From Basic To Trap.

以上是Golang Defer:堆疊分配、堆疊分配、開放式編碼的 Defer的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn