Middle+
What synchronization primitives are available for goroutines in Go? Fix the race condition example using atomic.
sobes.tech AI
Answer from AI
In Go, there are several tools for goroutine synchronization:
- Mutexes (
sync.Mutex) — for locking critical sections. - Channels (
chan) — for communication and synchronization. - The
sync/atomicpackage — for atomic operations on variables. sync.WaitGroup— for waiting for a group of goroutines to finish.
Example of a race condition and its fix using atomic:
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
var counter int64 = 0
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
atomic.AddInt64(&counter, 1) // atomic increment
}()
}
wg.Wait()
fmt.Println("Counter:", counter) // Expected 1000
}
In this example, without atomic.AddInt64, there would be a race condition when incrementing counter. Using atomic guarantees correct variable updates without locks.