Home  >  Article  >  Backend Development  >  Basic tutorial: Go WaitGroup and its application in Golang

Basic tutorial: Go WaitGroup and its application in Golang

王林
王林Original
2023-09-28 09:42:38991browse

基础教程:Go WaitGroup及其在Golang中的应用

Basic Tutorial: Go WaitGroup and its application in Golang, specific code examples are required

Foreword:
In Golang (Go language), writing concurrency Procedure is a common task. Golang provides a wealth of concurrency primitives and APIs, one of the important tools is WaitGroup. This article will introduce you to the concept and usage of WaitGroup and provide some specific code examples.

1. The concept of WaitGroup
WaitGroup is a concurrency primitive in Golang, which is used to wait for the completion of a group of goroutines. WaitGroup maintains a counter internally, with an initial value of 0. When each coroutine starts executing, the counter is incremented by 1. When the coroutine ends, the counter will be decremented by 1. The main thread can block through the Wait() method until the counter reaches 0, that is, all coroutines are executed.

2. Basic usage of WaitGroup
Using WaitGroup requires the following steps:

  1. Create a WaitGroup object: First, we need to import the "sync" package, and Create a WaitGroup object.

    import "sync"
    
    var wg sync.WaitGroup
  2. Add coroutine to WaitGroup: For each coroutine to be executed, we need to increment the counter and use the go keyword to perform the task in the new coroutine.

    wg.Add(1)
    go func() {
     // 协程的具体逻辑
     // ...
     wg.Done() // 协程执行完成后减少计数器
    }()
  3. Waiting for the completion of the coroutine: The main thread can use the Wait() method to block until the counter is 0, that is, all coroutines have been executed.

    wg.Wait()

Sample code:
The following is a specific code example that demonstrates the application of WaitGroup in Golang. This example uses WaitGroup to wait for multiple coroutines to complete before continuing with subsequent logic.

package main
 
import (
    "fmt"
    "sync"
    "time"
)
 
func main() {
    var wg sync.WaitGroup
 
    for i := 0; i < 5; i++ {
        wg.Add(1)
 
        go func(num int) {
            defer wg.Done()
            time.Sleep(time.Second) // 模拟长时间的任务
 
            fmt.Printf("协程 %d 完成
", num)
        }(i)
    }
 
    fmt.Println("等待所有协程完成...")
    wg.Wait()
    fmt.Println("所有协程已完成!")
}

In the above example, we simulated the execution of 5 coroutines, and each coroutine waited for 1 second. With WaitGroup, the main thread blocks until all coroutines are executed. In the output, we can see that the order in which the coroutines complete is not fixed because they are executed in parallel.

3. Notes on WaitGroup
When using WaitGroup, you need to follow the following precautions:

  1. Before calling Wait(), each coroutine must be Call Done() to ensure the counter is decremented. Otherwise the main thread will block forever.
  2. WaitGroup is passed by value, so when passing into a function or method, be sure to pass a pointer, not a copy of the value.
  3. Do not use multiple WaitGroup objects to wait for each other, this will cause deadlock.

Conclusion:
WaitGroup is a very useful concurrency primitive in Golang, which can conveniently wait for the completion of a group of coroutines. This article introduces the basic concepts and usage of WaitGroup and provides a specific code example. I hope that studying this article can help you better understand and apply the use of WaitGroup in Golang.

The above is the detailed content of Basic tutorial: Go WaitGroup and its application in Golang. 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