Principal
Which of the list are synchronization tools in Go? Channels, sync.WaitGroup, sync.Mutex, sync.Cond?.
sobes.tech AI
Answer from AI
In Go, the listed synchronization tools are:
- Channels: the primary and idiomatic way to synchronize and exchange data between goroutines.
- sync.WaitGroup: used to wait for a group of goroutines to finish.
- sync.Mutex: provides mutual exclusion to protect critical sections.
- sync.Cond: a conditional variable for more complex synchronization, such as waiting for a certain state.
All of these are synchronization tools in Go. They are used in different scenarios:
- Channels are good for data transfer and signaling.
- Mutexes are for protecting shared resources.
- WaitGroup is for waiting for multiple goroutines to complete.
- Cond is for implementing waiting and notification upon state changes.
Example of using WaitGroup and 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) // 2