首頁  >  文章  >  後端開發  >  golang函數與goroutine的資源分配

golang函數與goroutine的資源分配

王林
王林原創
2024-04-25 12:42:021046瀏覽

函數在執行時分配資源,執行完畢後自動釋放;而 goroutine 在創建時分配資源,需明確關閉或使用 context、WaitGroup 確保釋放,防止記憶體洩漏和效能下降。

golang函數與goroutine的資源分配

Golang 函數與Goroutine 的資源分配實戰

簡介

在Go 語言中,函數和goroutine 是常被使用的並發性機制。函數是執行程式碼的單元,而 goroutine 則是並發執行的函數。合理分配函數和 goroutine 的資源至關重要,以優化程式效能和防止資源浪費。

函數的資源分配

函數只在執行時佔用資源,執行完畢後會自動釋放所有資源。可以透過使用 defer 語句來確保資源在函數傳回前釋放。例如:

func cleanup() {
  // 释放资源
}

func main() {
  defer cleanup()
  // 执行代码
}

Goroutine 的資源分配

與函數不同,goroutine 在建立時分配資源,並且直到 goroutine 退出才釋放這些資源。如果不及時釋放 goroutine,會導致記憶體洩漏和效能下降。

有幾種方法可以確保goroutine 釋放資源:

  • #明確關閉channel 和other 資源:

    c := make(chan int)
    // 使用 channel
    close(c)
  • #使用context.Done()

    ctx, cancel := context.WithCancel(context.Background())
    // 使用 context
    cancel()
  • 透過WaitGroup# 等待goroutine退出:

    var wg sync.WaitGroup
    wg.Add(1)
    go func() {
      // 执行代码
      wg.Done()
    }()
    wg.Wait()

實戰案例

在以下範例中,我們建立了多個goroutine 來執行非同步任務:

package main

import (
  "context"
  "fmt"
  "sync"
)

func main() {
  ctx, cancel := context.WithCancel(context.Background())

  var wg sync.WaitGroup
  for i := 0; i < 10; i++ {
    wg.Add(1)
    go func(i int) {
      defer wg.Done()
      fmt.Println("Goroutine", i)

      // 使用 ctx 来响应取消请求
      select {
        case <-ctx.Done():
          fmt.Println("Goroutine", i, "cancelled")
          return
        default:
          // 继续执行任务
      }
    }(i)
  }

  // 取消所有 goroutine
  cancel()
  wg.Wait()
}

運行此程序,輸出如下:

Goroutine 0
Goroutine 1
Goroutine 2
Goroutine 3
Goroutine 4
Goroutine 5
Goroutine 0 cancelled
Goroutine 1 cancelled
Goroutine 2 cancelled
Goroutine 3 cancelled
Goroutine 4 cancelled
Goroutine 5 cancelled
Goroutine 6
Goroutine 7
Goroutine 8
Goroutine 9
Goroutine 6 cancelled
Goroutine 7 cancelled
Goroutine 8 cancelled
Goroutine 9 cancelled

從輸出中可以看出,當cancel() 函數被呼叫時,所有goroutine 都及時釋放了資源。

以上是golang函數與goroutine的資源分配的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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