Senior
What is a pessimistic lock?
sobes.tech AI
Answer from AI
Pessimistic locking is an approach to managing concurrent access to data, where a 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 lock 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 modifies data at a time, but it can lead to reduced parallelism and blocking.