Sobes.tech
Middle

What synchronization primitives are available in Go? Tell about WaitGroup and Mutex.

sobes.tech AI

Answer from AI

In Go, there are several primitives for synchronization to manage concurrent access to resources and coordinate goroutines:

  • Mutex — provides mutual exclusion by locking access to a critical section of code. It is used to protect shared data from concurrent modification.
  • WaitGroup — allows waiting for a set of goroutines to finish. Methods Add, Done, and Wait can be used to synchronize execution.
  • Channel — enables passing data between goroutines and can be used for synchronization.

WaitGroup

sync.WaitGroup is used to wait for multiple goroutines to complete. Example:

var wg sync.WaitGroup
wg.Add(3) // waiting for 3 goroutines

for i := 0; i < 3; i++ {
    go func(id int) {
        defer wg.Done() // signal completion
        fmt.Println("Goroutine", id)
    }(i)
}

wg.Wait() // wait until all Done are called

Mutex

sync.Mutex protects a critical section so that only one goroutine can execute it at a time:

var mu sync.Mutex
var counter int

func increment() {
    mu.Lock()   // lock
    defer mu.Unlock() // unlock
    counter++
}

Thus, WaitGroup helps wait for goroutines to finish, and Mutex protects data from concurrent access.

What synchronization primitives are available in Go… - sobes.tech