Home  >  Article  >  Backend Development  >  How to synchronize Goroutine using WaitGroup in Go?

How to synchronize Goroutine using WaitGroup in Go?

WBOY
WBOYOriginal
2024-06-01 21:18:00489browse

如何在 Go 中使用WaitGroup同步 Goroutine?

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:

  1. CreateWaitGroup
  2. ##
    var wg sync.WaitGroup
  1. Use Add()
  2. in goroutine
When a new goroutine starts executing, use

WaitGroup.Add(1) to increment the counter.

wg.Add(1)
go func() {
  // goroutine 代码
  wg.Done()
}()

  1. Use Done() in goroutine
When the goroutine completes execution, use

WaitGroup. Done() to decrement the counter.

func() {
  // goroutine 代码
  wg.Done()
}

  1. Wait for Goroutine to complete
Use

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 use

WaitGroup 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!

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