Sobes.tech
Junior — Middle

Can you explain how synchronization is implemented using Wait Group in Go?

sobes.tech AI

Answer from AI

In Go, synchronization with WaitGroup is implemented through a structure from the sync package, which allows waiting for a set of goroutines to complete.

Main methods:

  • Add(int) — increases the counter of expected goroutines.
  • Done() — decreases the counter, called upon goroutine completion.
  • Wait() — blocks execution until the counter reaches zero.

Example:

var wg sync.WaitGroup

wg.Add(2) // expecting 2 goroutines

go func() {
    defer wg.Done()
    // goroutine 1 work
}()

go func() {
    defer wg.Done()
    // goroutine 2 work
}()

wg.Wait() // wait for both goroutines to finish

Thus, WaitGroup allows efficient synchronization of multiple parallel tasks without using complex locking mechanisms.

Can you explain how synchronization is implemented… - sobes.tech