golockingdefer-keyword

mutex.Lock and defered mutex.Unock order


in golang, sync.Mutex Lock and Unlock are usaul operation,but what is the correct order of Lock and defer Unlock?

mu.Lock()
defer mu.Unlock()

or

defer mu.Unlock()
mu.Lock()

which is best?


Solution

  • It doesn't matter.

    Either way, defer causes mu.Unlock() to be executed when the current scope is exited (e.g. a function that returns).

    The first method it's preferable, because it has a more natural ordering (lock, then unlock) for human readability.