


Golang concurrent programming advanced: in-depth understanding of WaitGroup
Golang concurrent programming advanced: in-depth understanding of WaitGroup
Introduction:
Concurrent programming is one of the most powerful features of Golang. When executing multiple tasks in parallel, a common scenario is to wait for all tasks to complete before proceeding to the next step. The sync package in Golang provides a good tool WaitGroup to solve this problem. This article will provide an in-depth introduction to the use of WaitGroup and give specific code examples.
1. What is WaitGroup?
WaitGroup is a structure in the sync package in Golang. It provides a simple and effective mechanism to wait for all goroutines to complete their tasks. WaitGroup maintains a counter internally. The value of the counter can be increased through the Add() method, the value of the counter can be decreased by the Done() method, and the Wait() method is used to block the current thread until the counter returns to zero.
2. Basic usage of WaitGroup
First, we need to import the sync package:
import "sync"
Then, we can follow the following steps to use WaitGroup:
Create WaitGroup object:
var wg sync.WaitGroup
Copy after loginUse the Add() method to set the number of tasks to wait for:
wg.Add(2)
Copy after loginStart goroutine to execute tasks:
go task1() go task2()
Copy after loginCall the Done() method before the task ends to reduce the counter value:
func task1() { defer wg.Done() // 执行task1的操作 } func task2() { defer wg.Done() // 执行task2的操作 }
Copy after loginFinally, call it where you need to wait for all tasks to complete Wait() method:
wg.Wait()
Copy after loginIn this way, the main thread will wait for all tasks to be completed before continuing to the next step.
3. Practical application examples of WaitGroup
Below we use a specific example to illustrate the usage of WaitGroup.
Suppose we have a requirement to download multiple network images concurrently and save them locally. When all images are downloaded, we need to perform subsequent processing. The code example is as follows:
package main import ( "fmt" "io" "net/http" "os" "sync" ) var wg sync.WaitGroup func main() { // 假设有3个图片需要下载 imageUrls := []string{ "https://example.com/image1.jpg", "https://example.com/image2.jpg", "https://example.com/image3.jpg", } // 设置需要等待的任务数量 wg.Add(len(imageUrls)) // 并发下载图片 for _, imageUrl := range imageUrls { go downloadImage(imageUrl) } // 等待所有任务完成 wg.Wait() fmt.Println("所有图片下载完成,进行后续处理") } func downloadImage(imageUrl string) { defer wg.Done() // 发送HTTP GET请求获取图片数据 resp, err := http.Get(imageUrl) if err != nil { fmt.Printf("下载图片失败: %v ", err) return } defer resp.Body.Close() // 创建本地文件 fileName := imageUrl[strings.LastIndex(imageUrl, "/")+1:] imgFile, err := os.Create(fileName) if err != nil { fmt.Printf("创建图片文件失败: %v ", err) return } defer imgFile.Close() // 将图片数据保存到本地文件 _, err = io.Copy(imgFile, resp.Body) if err != nil { fmt.Printf("保存图片失败: %v ", err) return } fmt.Printf("图片下载成功: %v ", imageUrl) }
In the above example code, we first define a package-level variable wg to manage the counter waiting for task completion. In the main function, we set the number of waiting tasks to the number of image URLs, and then start each image download task concurrently. After each task is completed, call the wg.Done() method to decrement the counter value. Finally, call the wg.Wait() method to wait for all tasks to complete. When all images are downloaded, continue to perform subsequent processing.
Summary:
This article introduces in detail the use of WaitGroup in Golang, and gives a specific example of multi-tasking concurrent downloading of images. By in-depth understanding of the use of WaitGroup, you can better master Golang's concurrent programming capabilities and improve program performance and efficiency. In practical applications, we can flexibly use WaitGroup to manage and wait for the completion of multiple goroutines according to specific needs.
The above is the detailed content of Golang concurrent programming advanced: in-depth understanding of WaitGroup. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

The FindStringSubmatch function finds the first substring matched by a regular expression: the function returns a slice containing the matching substring, with the first element being the entire matched string and subsequent elements being individual substrings. Code example: regexp.FindStringSubmatch(text,pattern) returns a slice of matching substrings. Practical case: It can be used to match the domain name in the email address, for example: email:="user@example.com", pattern:=@([^\s]+)$ to get the domain name match[1].

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

Using predefined time zones in Go includes the following steps: Import the "time" package. Load a specific time zone through the LoadLocation function. Use the loaded time zone in operations such as creating Time objects, parsing time strings, and performing date and time conversions. Compare dates using different time zones to illustrate the application of the predefined time zone feature.

Go framework development FAQ: Framework selection: Depends on application requirements and developer preferences, such as Gin (API), Echo (extensible), Beego (ORM), Iris (performance). Installation and use: Use the gomod command to install, import the framework and use it. Database interaction: Use ORM libraries, such as gorm, to establish database connections and operations. Authentication and authorization: Use session management and authentication middleware such as gin-contrib/sessions. Practical case: Use the Gin framework to build a simple blog API that provides POST, GET and other functions.
