Sobes.tech
Senior

Which of the listed are synchronization tools in Go? Channels, sync.WaitGroup, sync.Mutex, sync.Cond?

sobes.tech AI

Answer from AI

In Go, all the listed tools — channels, sync.WaitGroup, sync.Mutex, and sync.Cond — are synchronization mechanisms, but they serve different purposes:

  • Channels — allow safe data exchange between goroutines and are used for synchronization through message passing.
  • sync.Mutex — a mutex for mutual exclusion, preventing concurrent access to shared resources.
  • sync.WaitGroup — allows waiting for a group of goroutines to finish, synchronizing their completion.
  • sync.Cond — a condition variable, used for more complex synchronization when goroutines wait for a certain condition to occur.

Example of using sync.WaitGroup and sync.Mutex:

var mu sync.Mutex
var wg sync.WaitGroup
counter := 0

wg.Add(2)
go func() {
    defer wg.Done()
    mu.Lock()
    counter++
    mu.Unlock()
}()
go func() {
    defer wg.Done()
    mu.Lock()
    counter++
    mu.Unlock()
}()
wg.Wait()
fmt.Println("Counter:", counter)