I have the following code structure where I Lock() at point A and need to definitely Unlock() at a point B in the same function. Between point A and B, I have multiple returns b
It is not possible to cancel a deferred function.
Use a local variable to record the function's state with respect to the lock and check that variable in the deferred function.
lock.Lock()
locked := true
defer func() {
if locked {
lock.Unlock()
}
}()
...
err := bar()
if err != nil {
return
}
...
lock.Unlock()
locked = false
...
Because locks are generally used in a multithreaded environment, it should be noted that the function local variable locked
should only accessed by a single goroutine (thank you Rick-777 for calling this out in a comment).