How to cancel a deferred statement

后端 未结 2 851
时光取名叫无心
时光取名叫无心 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条回答
  •  旧时难觅i
    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).

提交回复
热议问题