How to cancel a deferred statement

限于喜欢 提交于 2020-08-20 05:46:28

问题


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() ?
}

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/61240777/how-to-cancel-a-deferred-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!