Home > Article > Backend Development > How to use Go WaitGroup to handle concurrent tasks
How to use Go WaitGroup to handle concurrent tasks
In the Go language, we can handle concurrent tasks by using sync.WaitGroup
. sync.WaitGroup
can provide a concise and effective way to coordinate the execution of coroutines when handling concurrent tasks.
sync.WaitGroup
is a useful tool and is the preferred method for handling concurrent tasks when we don't know how many coroutines need to wait. It allows us to ensure that the main coroutine does not end execution until all tasks are completed.
Let's look at a specific example showing how to use sync.WaitGroup
to handle concurrent tasks.
First, we need to import the sync
package:
import ( "fmt" "sync" )
Next, let us create a sync.WaitGroup
object:
var wg sync.WaitGroup
Then, we can add the number of tasks to wait by calling the Add
method. In this example, we will add two tasks:
wg.Add(2)
Next, we can start two coroutines to perform the tasks. We can encapsulate the task in an anonymous function and pass it as a parameter to the go
keyword.
go func() { defer wg.Done() // 这里是第一个任务的代码逻辑 }() go func() { defer wg.Done() // 这里是第二个任务的代码逻辑 }()
In this example, we put defer wg.Done()
inside each coroutine after the go
keyword to ensure that after the task is completed Able to notify the WaitGroup
object.
Finally, we can execute the Wait
method to block the main coroutine until all tasks are completed. This method reduces the number of tasks in the WaitGroup object to zero.
wg.Wait()The following is the complete sample code:
package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() fmt.Println("Task 1 executed") }() go func() { defer wg.Done() fmt.Println("Task 2 executed") }() wg.Wait() fmt.Println("All tasks completed") }Run this code, you will see that the output prints the execution results of the two tasks, and then prints "All tasks completed". By using
sync.WaitGroup, we can easily handle concurrent tasks and ensure that all tasks are completed before continuing the execution of the main coroutine. This is especially useful when you need to wait for all tasks to be completed in the main coroutine, such as crawlers, parallel computing and other scenarios.
sync.WaitGroup can help us handle concurrent tasks in the Go language. It provides a concise and effective way to coordinate the execution of the coroutine and ensure that all tasks are completed before continuing the execution of the main coroutine. I hope this article helps you understand concurrent task processing.
The above is the detailed content of How to use Go WaitGroup to handle concurrent tasks. For more information, please follow other related articles on the PHP Chinese website!