Other have provided some options. Another option is to use a sentinel value 
and check. It is less than ideal for many reasons, but in some cases is 
still the best option. In your case it might be to use nil:
var m sync.Mutex
lock := &m
lock.Lock()
defer func() {if lock != nil {lock.Unlock()}}()
if err := performOperation1(); err != nil {
    return err
}
lock.Unlock()
lock = nil
performExpensiveOperation2()



On Friday, February 8, 2019 at 1:28:12 PM UTC-5, vincent163 wrote:
>
> I am thinking about how to write programs like this:
> lock1.Lock()
> err = performOperation1()
> if err != nil {
>   lock1.Unlock()
>   return err
> }
> lock1.Unlock()
> performExpensiveOperation2()
>
> The lock1 must be locked while performing operation1, and I need to use 
> its result to perform operation2. Since operation2 is expensive, I don't 
> want to hold the lock while performing it, and lock1.Unlock() needs to be 
> called before calling operation2.
> Go's defer mechanism doesn't seem to handle this case well since the 
> resource is used only within a block and not throughout the function. Is 
> there a recommended way to write programs in this case?
> I know I could wrap the lock block in a closure, but that creates a 
> completely new scope, so I can't return directly or break out of a loop 
> within the closure, etc.
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to