snippetgoModeratepending
Go sync patterns -- Mutex, WaitGroup, Once, and channels
Viewed 0 times
MutexWaitGroupOncechannelsyncgoroutinedata race
go
Problem
Concurrent Go code needs synchronization. Data races cause unpredictable bugs. Need to coordinate goroutines safely.
Solution
Use the right sync primitive for each case: Mutex for shared state, WaitGroup for waiting on goroutines, Once for one-time init, channels for communication.
Code Snippets
Go sync primitives: Mutex, WaitGroup, Once
import "sync"
// Mutex: protect shared state
type SafeCounter struct {
mu sync.RWMutex
v map[string]int
}
func (c *SafeCounter) Inc(key string) {
c.mu.Lock()
defer c.mu.Unlock()
c.v[key]++
}
func (c *SafeCounter) Get(key string) int {
c.mu.RLock() // multiple readers OK
defer c.mu.RUnlock()
return c.v[key]
}
// WaitGroup: wait for goroutines
var wg sync.WaitGroup
for _, url := range urls {
wg.Add(1)
go func(u string) {
defer wg.Done()
fetch(u)
}(url)
}
wg.Wait()
// Once: thread-safe singleton
var instance *DB
var once sync.Once
func GetDB() *DB {
once.Do(func() { instance = connectDB() })
return instance
}Revisions (0)
No revisions yet.