Home > Article > Backend Development > How to synchronize Goroutine using WaitGroup in Go?
How to use WaitGroup to synchronize Goroutine in Go?
What is WaitGroup
?
WaitGroup
is a built-in type in Go that is used to coordinate concurrent operations. It can be used to ensure that a group of goroutines does not continue execution until it has completed execution.
How to use WaitGroup
The steps to use WaitGroup
are as follows:
WaitGroup
var wg sync.WaitGroup
WaitGroup.Add(1) to increment the counter.
wg.Add(1) go func() { // goroutine 代码 wg.Done() }()
WaitGroup. Done() to decrement the counter.
func() { // goroutine 代码 wg.Done() }
WaitGroup.Wait() to block the current goroutine until all associated goroutines Complete execution.
wg.Wait()
Practical case
The following is an example that demonstrates how to useWaitGroup to synchronize three concurrent goroutines:
package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup // 创建三个并发 goroutine for i := 0; i < 3; i++ { wg.Add(1) go func(i int) { defer wg.Done() fmt.Printf("Goroutine %d complete\n", i) }(i) } // 等待所有 goroutine 完成执行 wg.Wait() // 输出:Goroutine 0 complete // 输出:Goroutine 1 complete // 输出:Goroutine 2 complete fmt.Println("All goroutines completed") }
The above is the detailed content of How to synchronize Goroutine using WaitGroup in Go?. For more information, please follow other related articles on the PHP Chinese website!