Junior — Middle
Kas saaks selgitada, mis on vastastikune välistus (Mutex) ja kuidas see töötab?
sobes.tech AI
Vastus AI-lt
Mutual exclusion (Mutex) is a synchronization mechanism that guarantees that at any given moment, only one goroutine (thread) can access a specific resource or critical section of code.
In Go, this is achieved using the sync.Mutex type. When a goroutine calls Lock(), it locks the mutex, and other goroutines attempting to call Lock() will wait until the mutex is unlocked with Unlock().
Example:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
In this example, increment safely increases the value of counter, preventing concurrent access from multiple goroutines.