Home >Backend Development >Golang >Efficient Concurrent Programming: Practical Tips for Using Golang WaitGroup

Efficient Concurrent Programming: Practical Tips for Using Golang WaitGroup

王林
王林Original
2023-09-27 17:48:37798browse

高效并发编程:使用Golang WaitGroup的实践技巧

Efficient concurrent programming: Practical skills using Golang WaitGroup

Introduction: In today's software development field, concurrent programming is a very important skill. As a high-performance programming language, Golang provides rich concurrent programming mechanisms and tools. Among them, WaitGroup is a very practical tool for thread synchronization in Golang. In this article, we will explore how to use WaitGroup for efficient concurrent programming and provide some practical example code.

1. Understand WaitGroup

Before we begin, let’s first understand what WaitGroup is. WaitGroup is a concurrency primitive in Golang that can be used to wait for a group of goroutines to complete tasks. Simply put, WaitGroup can help us proceed to the next step after all goroutines have completed their tasks.

2. Basic methods of using WaitGroup

There are three basic methods of using WaitGroup: Add, Done and Wait.

  1. Add method: Used to tell WaitGroup how many goroutines we still need to wait for. The parameter of the Add method is of type int, indicating the number of waiting goroutines.
  2. Done method: used to tell WaitGroup that a goroutine has completed its task. Each time the Done method is called, the number of waiting goroutines will be reduced by one.
  3. Wait method: used to wait for all goroutines to complete their tasks. When the number of waiting goroutines is reduced to 0, the Wait method will return.

3. Practical skills

Next, we will use some actual sample code to demonstrate how to use WaitGroup for efficient concurrent programming.

Example 1: Simple concurrent tasks

Suppose we have a task list, need to execute tasks in parallel, and wait for all tasks to be executed to print the results. This function can be easily implemented using WaitGroup.

package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup

    tasks := []string{"task1", "task2", "task3", "task4"}

    for _, t := range tasks {
        wg.Add(1)
        go func(task string) {
            defer wg.Done()

            // 执行任务,这里假设执行耗时为1秒
            // ...

            fmt.Printf("任务 %s 执行完毕
", task)
        }(t)
    }

    wg.Wait()

    fmt.Println("所有任务执行完毕!")
}

In the above example, we first created a WaitGroup instance wg. Then, by looping through the task list, use the Add method to tell the WaitGroup that there is a goroutine to wait for. Next, we start a coroutine to execute the task, and use the Done method to tell the WaitGroup that the goroutine has been completed after the task is executed. Finally, call the Wait method to wait for all goroutines to complete execution.

Example 2: Concurrent Download

In this example, we need to download multiple files at the same time and summarize the results after all files are downloaded. This function can be easily implemented using WaitGroup.

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "sync"
)

func main() {
    var wg sync.WaitGroup

    urls := []string{"http://example.com/file1.txt", "http://example.com/file2.txt", "http://example.com/file3.txt"}

    for _, url := range urls {
        wg.Add(1)
        go func(url string) {
            defer wg.Done()

            resp, err := http.Get(url)
            if err != nil {
                fmt.Printf("下载 %s 失败:%s
", url, err.Error())
                return
            }

            defer resp.Body.Close()

            body, err := ioutil.ReadAll(resp.Body)
            if err != nil {
                fmt.Printf("读取 %s 内容失败:%s
", url, err.Error())
                return
            }

            fmt.Printf("下载 %s 完成,文件大小:%d 字节
", url, len(body))
        }(url)
    }

    wg.Wait()

    fmt.Println("所有文件下载完成!")
}

In the above example, we also use WaitGroup to implement concurrent downloads. By looping through the download address list, use the Add method to tell the WaitGroup that there is a goroutine to wait for. In each goroutine, we use http package to send GET request and get the file content. Finally, use the Done method to tell the WaitGroup that the goroutine has completed. Finally, call the Wait method to wait for all goroutines to complete execution.

Conclusion: This article introduces how to use Golang's WaitGroup to achieve efficient concurrent programming. By properly using the Add, Done, and Wait methods, we can easily control the execution process of concurrent tasks and improve the performance and efficiency of the program. When you are writing concurrent programs, you might as well try using WaitGroup to synchronize tasks. I believe it will bring you a lot of convenience and surprises!

The above is the detailed content of Efficient Concurrent Programming: Practical Tips for Using Golang WaitGroup. 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