Middle+
How to solve the race condition problem when adding products to the same cart from different goroutines?
sobes.tech AI
Answer from AI
The race condition problem when adding items to the same cart from different goroutines in Go can be solved by synchronizing access to the shared data structure. The simplest way is to use a mutex (sync.Mutex) to protect the critical section where the cart is modified.
Example:
import (
"sync"
)
type Cart struct {
mu sync.Mutex
items map[string]int
}
func (c *Cart) AddItem(productID string, quantity int) {
c.mu.Lock()
defer c.mu.Unlock()
c.items[productID] += quantity
}
// Usage
cart := &Cart{items: make(map[string]int)}
// In different goroutines
// go cart.AddItem("product1", 2)
// go cart.AddItem("product1", 3)
Alternatively, channels can be used for sequential processing of cart modifications, but a mutex is a more direct and simple method.