ホームページ  >  記事  >  バックエンド開発  >  Golang Defer: ヒープ割り当て、スタック割り当て、オープンコード遅延

Golang Defer: ヒープ割り当て、スタック割り当て、オープンコード遅延

WBOY
WBOYオリジナル
2024-08-07 18:10:56268ブラウズ

これは投稿の抜粋です。投稿全文はこちらからご覧いただけます: Golang Defer: 基本からトラップまで。

defer ステートメントは、おそらく Go を学習し始めるときに最初に非常に興味深いと思うものの 1 つですよね?

しかし、多くの人がつまずくのはそれだけではありません。また、それを使用するときに触れていない魅力的な側面もたくさんあります。

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 を使用したため、メインが終了する前の最後のステップとして「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 ステートメントを呼び出すたびに、次のようにその関数が現在のゴルーチンのリンク リストの先頭に追加されます。

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

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 内のすべての遅延関数がトレースされて実行されるという典型的なケースが 1 つあり、そのときにパニックが発生します。

延期、パニック、回復

コンパイル時エラーの他に、ゼロ除算 (整数のみ)、範囲外、nil ポインタの逆参照などの実行時エラーが多数あります。これらのエラーにより、アプリケーションはパニックを起こします。

パニックは、現在の 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: ヒープ割り当て、スタック割り当て、オープンコード遅延の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。