Junior — Middle
Milliseid ülesandeid lahendab sync pakett Go programmeerimiskeeles?
sobes.tech AI
Vastus AI-lt
The sync package in Go provides synchronization primitives for managing concurrent access to resources and coordinating goroutines.
Main tasks solved by the sync package:
- Mutex (
Mutex) — to protect critical sections and prevent simultaneous access to shared data. - RWMutex — a mutex with separation for reading and writing, allowing multiple goroutines to read data simultaneously but blocking writing.
- WaitGroup — to wait for a group of goroutines to finish.
- Once — to perform initialization only once.
Example of using Mutex:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
Thus, the sync package helps to work safely with concurrency and avoid race conditions.