How to cancel a deferred statement

后端 未结 2 850
时光取名叫无心
时光取名叫无心 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.

提交回复
热议问题