Home  >  Article  >  Backend Development  >  Concurrency control instance analysis: Use Go WaitGroup to complete tasks in Golang

Concurrency control instance analysis: Use Go WaitGroup to complete tasks in Golang

王林
王林Original
2023-09-28 09:09:38865browse

并发控制实例解析:Golang中使用Go WaitGroup完成任务

Concurrency control instance analysis: Using Go WaitGroup to complete tasks in Golang requires specific code examples

Introduction:
In concurrent programming, you often encounter the need A situation where you wait for a set of tasks to complete before proceeding to the next step. In Golang, we can use WaitGroup in the sync package to achieve this function. This article will introduce how to use WaitGroup to complete task concurrency control, and give specific code examples for readers' reference.

  1. Understand the basic concepts of WaitGroup
    WaitGroup is a very useful concurrency control tool in Golang, which can be used to wait for the completion of a group of tasks. When we need to wait for a group of goroutines to complete before performing the next step, we can use WaitGroup to achieve this purpose.

WaitGroup has three main methods:

  • Add(delta int): Add or reduce the number of waiting goroutines to WaitGroup. delta can be a positive or negative number. . For example, a delta of 1 means adding a waiting goroutine, and a delta of -1 means completing a waiting goroutine.
  • Done(): Marks that a waiting goroutine has been completed, equivalent to Add(-1).
  • Wait(): Blocks and waits until all waiting goroutines are completed.
  1. Example of using WaitGroup to implement task concurrency control
    The following is a simple example to demonstrate how to use WaitGroup to implement concurrent task control.

Suppose we need to download multiple files, and each file download requires an independent goroutine to process. Our goal is to start multiple goroutines at the same time to download these files, and proceed to the next step after all downloads are completed.

First, we need to create a WaitGroup object and set its initial value equal to the number of files to be downloaded:

var wg sync.WaitGroup
const numFiles = 5

func main() {
    wg.Add(numFiles)
    // 启动goroutine执行下载任务
    for i := 0; i < numFiles; i++ {
        go downloadFile(i)
    }
    // 等待所有的下载任务完成
    wg.Wait()
    // 所有的下载任务已完成,进行下一步操作
    fmt.Println("All files have been downloaded!")
}

In the downloadFile function, we need the specific logic of downloading files. When a file is downloaded, we need to call WaitGroup's Done method to mark that the goroutine has been completed:

func downloadFile(fileIndex int) {
    defer wg.Done()
    // 具体的文件下载逻辑
    fmt.Printf("Downloading file %d...
", fileIndex)
    time.Sleep(time.Second) // 模拟文件下载的耗时操作
    fmt.Printf("File %d has been downloaded.
", fileIndex)
}

In the download logic, we notify WaitGroup that a waiting goroutine has been completed by calling WaitGroup's Done method. When all goroutines call the Done method, the main goroutine will be released after calling the Wait method and continue to perform subsequent operations.

  1. Example running results
    When we run the above code, we can see that the download process is performed concurrently. The download of each file is executed through different goroutines, and their execution order is undefined.

The output results are as follows:

Downloading file 0...
Downloading file 1...
Downloading file 2...
Downloading file 3...
Downloading file 4...
File 0 has been downloaded.
File 2 has been downloaded.
File 3 has been downloaded.
File 1 has been downloaded.
File 4 has been downloaded.
All files have been downloaded!

It can be seen that all files are downloaded by the goroutine started at the same time, and after all downloads are completed, the main goroutine continues to perform the next step. , print out "All files have been downloaded!".

Conclusion:
By using WaitGroup in Golang, we can easily achieve concurrency control of tasks. It not only improves the execution efficiency of the program, but also simplifies the writing process of concurrent tasks. I hope the sample code in this article will be helpful to readers and help them better master the usage skills of concurrency control in Golang.

The above is the detailed content of Concurrency control instance analysis: Use Go WaitGroup to complete tasks 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