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.
WaitGroup has three main methods:
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.
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!