How to synchronize Goroutine using WaitGroup in Go?

WBOY
Release: 2024-06-01 21:18:00
Original
425 people have browsed it

如何在 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
    Copy after login
  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()
}()
Copy after login

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

WaitGroup. Done() to decrement the counter.

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

  1. Wait for Goroutine to complete
Use

WaitGroup.Wait() to block the current goroutine until all associated goroutines Complete execution.

wg.Wait()
Copy after login

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")
}
Copy after login

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!

Related labels:
go
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!