Programming Languages
Go
Subjective
Oct 04, 2025
Explain the sync package and its primitives.
Detailed Explanation
Sync Package Primitives:
• Mutex: Mutual exclusion lock
• RWMutex: Reader-writer lock
• WaitGroup: Wait for goroutines
• Once: Execute function once
• Cond: Condition variables
• Pool: Object pool
• Map: Concurrent map
Examples:
// Mutex
var mu sync.Mutex
mu.Lock()
defer mu.Unlock()
// WaitGroup
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
// work
}(i)
}
wg.Wait()
// Once
var once sync.Once
once.Do(func() {
// initialization
})
// Pool
var pool = sync.Pool{
New: func() interface{} {
return make([]byte, 1024)
},
}
buf := pool.Get().([]byte)
defer pool.Put(buf)
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts