Junior — Middle
Have you used the pessimistic locking mechanism in your projects?
sobes.tech AI
Answer from AI
Yes, in Go projects I have used pessimistic locking when it was necessary to guarantee exclusive access to a resource.
Pessimistic locking assumes that when working with shared data, access is blocked for other goroutines until the operation is complete to avoid conflicts.
In Go, this is usually done using:
sync.Mutex— a mutex for mutual exclusion.sync.RWMutex— to separate locks for reading and writing.
Example of using sync.Mutex:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
This approach helps prevent data races but can reduce parallelism, so it is important to use locks judiciously.