Reputation: 71
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?
Upvotes: 0
Views: 2201
Reputation: 31199
A defer statement defers the execution of a function until the surrounding function returns.
The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
Both of your variants are identical because it doesn't matter where defer
red functions are placed it will be executed after the surrounding function returns.
Note if you have several defer
red functions it will be executed in reversed order accordingly to an order of defer
s declaration.
Upvotes: 0
Reputation: 12885
I see first variant more natural and easily readable. You may see as a lock gets acquired and at the same code piece it gets prepared to release:
mu.Lock()
defer mu.Unlock()
Anyway deferred function call will be executed later - at function exit.
Upvotes: 2
Reputation: 63397
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.
Upvotes: 6