How to cancel a deferred statement

后端 未结 2 849
时光取名叫无心
时光取名叫无心 2021-01-23 12:53

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

相关标签:
2条回答
  • 2021-01-23 13:42

    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.

    0 讨论(0)
  • 2021-01-23 13:44

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

    0 讨论(0)
提交回复
热议问题