Junior — Middle
Millist rolli mängivad sünkronsusprimitiivid Go programmeerimiskeeles?
sobes.tech AI
Vastus AI-lt
Synchronization primitives in Go are used to manage access to shared resources and coordinate the execution of goroutines, to prevent race conditions and ensure program correctness.
Main primitives:
- Mutex (sync.Mutex) — provides mutual exclusion, allowing only one goroutine to execute the critical section at a time.
- WaitGroup (sync.WaitGroup) — allows waiting for a group of goroutines to finish.
- Channel — a data transfer channel between goroutines, which is itself a powerful synchronization primitive.
- RWMutex (sync.RWMutex) — allows multiple goroutines to read data simultaneously, but writing blocks all.
Example of using Mutex:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
Thus, synchronization primitives help prevent conflicts during parallel data access and ensure proper interaction between goroutines.