doudeng1870 2017-11-22 05:08
浏览 247
已采纳

互斥锁锁定和延迟互斥锁解锁顺序

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?

  • 写回答

3条回答 默认 最新

  • dth20986 2017-11-22 05:10
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?