Middle+
What is in the sync package?
sobes.tech AI
Answer from AI
The sync package in Go provides synchronization primitives for managing concurrent access to resources.
Main components of the package:
Mutex— a mutex for mutual exclusion, blocks access to a resource.RWMutex— a read-write mutex, allows multiple readers or one writer at a time.WaitGroup— allows waiting for a group of goroutines to finish.Once— ensures a function is only executed once.Cond— a condition variable for signaling and waiting for events.
Example of using Mutex:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
This package is essential for safe handling of shared data in concurrent programs.