Middle+
What synchronization primitives for goroutines exist in Go?
sobes.tech AI
Answer from AI
In Go, the following primitives are used for goroutine synchronization:
- Mutex (sync.Mutex) — provides mutual exclusion, blocking access to shared resources.
- RWMutex (sync.RWMutex) — an extension of Mutex that allows multiple goroutines to read simultaneously but blocks writing.
- WaitGroup (sync.WaitGroup) — allows waiting for a set of goroutines to finish.
- Channel (chan) — a data transfer medium between goroutines, providing synchronization through message passing.
- Once (sync.Once) — guarantees that a specific function is executed only once.
- Cond (sync.Cond) — a condition variable for more complex synchronization, such as waiting for a certain state.
Example of using WaitGroup and Mutex:
var mu sync.Mutex
var wg sync.WaitGroup
var counter int
func increment() {
defer wg.Done()
mu.Lock()
counter++
mu.Unlock()
}
func main() {
wg.Add(3)
go increment()
go increment()
go increment()
wg.Wait()
fmt.Println("Counter:", counter)
}