Senior
What problems can arise from a race condition when updating a user's balance, and what are some solutions in Go?
sobes.tech AI
Answer from AI
When updating a user's balance in a concurrent environment, a race condition may occur when multiple goroutines read and write the balance value simultaneously, leading to incorrect results (e.g., lost updates).
Problems:
- Inconsistent balance state due to concurrent writes.
- Data loss during simultaneous increments or decrements.
Solutions in Go:
- Mutexes (
sync.Mutex) Use a mutex to protect the critical section where the balance is read and written.
var mu sync.Mutex
var balance int
func updateBalance(amount int) {
mu.Lock()
defer mu.Unlock()
balance += amount
}
- Atomic operations (
sync/atomic) For simple numeric types, atomic functions likeatomic.AddInt64can be used.
import "sync/atomic"
var balance int64
func updateBalance(amount int64) {
atomic.AddInt64(&balance, amount)
}
- Channels Organize sequential access to the balance through a channel, passing update operations to a dedicated goroutine.
type operation struct {
amount int
done chan bool
}
var ops = make(chan operation)
func balanceManager() {
var balance int
for op := range ops {
balance += op.amount
op.done <- true
}
}
func updateBalance(amount int) {
done := make(chan bool)
ops <- operation{amount, done}
<-done
}
func main() {
go balanceManager()
updateBalance(100)
}
The choice of method depends on the complexity of the task and performance requirements.