Senior
How to synchronize access of multiple goroutines to a shared object in the heap?
sobes.tech AI
Answer from AI
To synchronize access of multiple goroutines to a shared object in Go, mechanisms from the sync package are usually used:
- Mutex (
sync.Mutex) — blocks access to the resource, allowing one goroutine to work with the object while others wait. - RWMutex (
sync.RWMutex) — allows multiple goroutines to read the object simultaneously but blocks writing if someone is writing.
Example using sync.Mutex:
import (
"sync"
)
type SafeCounter struct {
mu sync.Mutex
count int
}
func (c *SafeCounter) Inc() {
c.mu.Lock()
defer c.mu.Unlock()
c.count++
}
func (c *SafeCounter) Value() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.count
}
Thus, before accessing the shared object, the goroutine locks the mutex, and after finishing, it unlocks it. This prevents data races and ensures correct operation with shared data.