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
You can't cancel a deferred function.
You could use sync.Once
to ensure that the mutex is unlocked exactly once:
func foo() {
var unlockOnce sync.Once
// point A
lock.Lock()
defer unlockOnce.Do(lock.Unlock)
...
err := bar()
if err != nil {
return
}
...
// point B - need to unlock here
unlockOnce.Do(lock.Unlock)
}
If possible, it is probably better to refactor your code so that the locked portion remains in a single function:
func fooLock() error {
lock.Lock()
defer lock.Unlock()
if err := bar(); err != nil { return err }
...
return nil
}
func foo() {
if err := fooLock(); err != nil { return }
... do the bit that doesn't need a lock
}
Obviously naming and error handling here is lax because the code is generic and not specific. If you need information from the block of code before your point B, which is now in code in fooLock
, it can be returned along with the error.