Senior
Task with goroutines and counter: will there be races? How to fix? What is the difference between Mutex and Atomic?
sobes.tech AI
Answer from AI
If multiple goroutines simultaneously increment a shared counter without synchronization, data races occur — the result can be unpredictable due to concurrent read and write.
To fix this, you can use:
- sync.Mutex — locks access to the counter, ensuring that only one goroutine modifies the value at a time.
- atomic operations from the
sync/atomicpackage — allow atomic increments without locks.
Difference between Mutex and Atomic:
- Mutex — a locking mechanism that stops other goroutines while the current one works with the protected resource. Suitable for complex operations with multiple steps.
- Atomic — a set of low-level operations that guarantee atomicity of variable modification without locks, usually faster but limited to simple operations (e.g., increment).
Example with Mutex:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
counter++
mu.Unlock()
}
Example with atomic:
import "sync/atomic"
var counter int64
func increment() {
atomic.AddInt64(&counter, 1)
}