Junior — Middle
Milliseid vastastikuse välistamise lukustusmehhanisme kasutate oma projektides?
sobes.tech AI
Vastus AI-lt
In Go, to implement mutual exclusion, I most often use the standard sync.Mutex type. It is simple to use and effectively blocks critical sections of code.
I also use sync.RWMutex when I need to differentiate access for reading and writing: several goroutines can read data simultaneously, but writing blocks everyone.
In some cases, I use channels for synchronization, which allows avoiding explicit locks and makes the code more declarative.
Example with sync.Mutex:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
Thus, the choice of mechanism depends on the specific task and performance requirements.