wenyi liu
wenyi liu

Reputation: 71

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?

Upvotes: 0

Views: 2201

Answers (3)

I159
I159

Reputation: 31199

defer

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 deferred functions are placed it will be executed after the surrounding function returns.

Note if you have several deferred functions it will be executed in reversed order accordingly to an order of defers declaration.

Upvotes: 0

Eugene Lisitsky
Eugene Lisitsky

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

Alexander
Alexander

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

Related Questions