AlphaEpsilon
AlphaEpsilon

Reputation: 151

How to cancel a deferred statement

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 based on errors where I would need to Unlock(). Using defer lock.Unlock() at point A solves the problem that in case there are errors the lock would be released. However, if execution successfully reaches point B - how can I cancel that defer and Unlock() anyway?

func foo() {
    ...
    // point A
    lock.Lock()
    defer lock.Unlock()
    ...
    err := bar()
    if err != nil {
        return
    }
    ...
    //point B - need to definetely unlock here
    //lock.Unlock() ?
}

Upvotes: 2

Views: 4997

Answers (2)

Thundercat
Thundercat

Reputation: 121119

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).

Upvotes: 3

Paul Hankin
Paul Hankin

Reputation: 58339

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.

Upvotes: 5

Related Questions