Junior — Middle
Kas on võimalik samaaegselt kasutada mitmeid lukustamise mehhanisme (Mutex) ühes funktsioonis?
sobes.tech AI
Vastus AI-lt
Yes, in Go it is possible to use multiple mutexes (Mutex) within the same function simultaneously. This is common when you need to protect different resources or parts of data that are not related to each other. The main thing is to avoid deadlocks, where one mutex waits for another to be released, and that one, in turn, waits for the first.
Example of using multiple mutexes:
var mu1 sync.Mutex
var mu2 sync.Mutex
func updateResources() {
mu1.Lock()
defer mu1.Unlock()
// Work with the first resource
mu2.Lock()
defer mu2.Unlock()
// Work with the second resource
}
To avoid deadlocks, it is recommended to always lock mutexes in the same order in all parts of the code.