Senior
Mis on pessimistic locking?
sobes.tech AI
Vastus AI-lt
Pessimistic locking is an approach to managing concurrent access to data, where the resource is locked immediately at the start of an operation to prevent conflicts. That is, when a transaction wants to modify data, it acquires a lock, and other transactions wait until the lock is released.
In Go, this can be implemented using mutexes (sync.Mutex), which block access to shared data:
var mu sync.Mutex
func updateData() {
mu.Lock() // pessimistic lock
defer mu.Unlock()
// critical section
}
This approach guarantees that only one goroutine can modify data at a time, but it may reduce parallelism and cause locking.