Home  >  Article  >  Backend Development  >  Resource allocation of golang functions and goroutine

Resource allocation of golang functions and goroutine

王林
王林Original
2024-04-25 12:42:021046browse

The function allocates resources during execution and is automatically released after execution; while goroutine allocates resources when created and needs to be explicitly closed or use context or WaitGroup to ensure release to prevent memory leaks and performance degradation.

Resource allocation of golang functions and goroutine

Practical resource allocation of Golang functions and Goroutines

Introduction

In the Go language, functions and goroutines are commonly used concurrency sexual mechanism. A function is a unit of code execution, and a goroutine is a function that is executed concurrently. Proper allocation of resources to functions and goroutines is crucial to optimize program performance and prevent resource waste.

Resource allocation of functions

The function only occupies resources during execution and automatically releases all resources after execution. You can ensure that resources are released before the function returns by using the defer statement. For example:

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

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

Goroutine's resource allocation

Unlike functions, goroutines allocate resources when they are created, and these resources are not released until the goroutine exits. If goroutine is not released in time, memory leaks and performance degradation will occur.

There are several ways to ensure that goroutine releases resources:

  • Explicitly close the channel and other resources:

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

    ctx, cancel := context.WithCancel(context.Background())
    // 使用 context
    cancel()
  • Wait for goroutine through WaitGroup Exit:

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

Practical case

In the following example, we create multiple goroutines to perform asynchronous tasks:

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()
}

Run The output of this program is as follows:

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

As can be seen from the output, when the cancel() function is called, all goroutines release resources in time.

The above is the detailed content of Resource allocation of golang functions and goroutine. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn