doukui4836 2018-11-26 14:32
浏览 39
已采纳

具有匿名互斥锁和结构的死锁

Let's say I have these two structs:

type A struct {
    Mutex sync.Mutex
    i int
}

type B struct {
    A
    sync.Mutex
}

Now, when I try to lock B and then A I got a deadlock:

var b B
b.Lock()
b.Mutex.Lock()
b.Mutex.Unlock()
b.Unlock()

I figured out that this is related with the name of the mutex of the struct A, for example, there is no deadlock if I name it Mutexx and not Mutex. But I don't know why it matters. Can anyone, please, explain this behavior?

https://play.golang.org/p/UVi_WLWeGmi

  • 写回答

1条回答 默认 最新

  • dtvjl64442 2018-11-26 14:36
    关注

    The reason for the deadlock is because your code will call the Lock() method of the same mutex twice, which is a blocking operation.

    The explanation lies in Spec: Selectors:

    The following rules apply to selectors:

    1. For a value x of type T or *T where T is not a pointer or interface type, x.f denotes the field or method at the shallowest depth in T where there is such an f. If there is not exactly one f with shallowest depth, the selector expression is illegal.

    What does this mean?

    In B, you embed both a sync.Mutex and a value of A, and A also embeds a sync.Mutex.

    When you write B.Mutex, that could refer to the directly embedded B.Mutex field (the unqualified type name acts as the field name), and could also refer to B.A.Mutex (because the A field is embedded in B), but according to the quoted rule above, it will denote the field / method at the shallowest depth which is B.Mutex.

    Similarly, b.Lock() could refer to B.Mutex.Lock() and could refer to B.A.Mutex.Lock(). But again according to the quoted rule, it will denote the field / method at the shallowest depth, which is B.Mutex.Lock().

    So this code:

    b.Lock()
    b.Mutex.Lock()
    

    Will call the Lock() method of the same Mutex twice, which is the embedded B.Mutex field of the B struct. The 2nd call will block, as the mutex is already locked.

    When you rename A.Mutex to e.g. A.Mutexx, and then you write:

    b.Lock()
    b.Mutexx.Lock()
    

    The first b.Lock() call refers to B.Mutex.Lock(), and the second b.Mutexx.Lock() call refers to B.A.Mutexx.Lock() call, so they lock 2 different, distinct mutexes; they are independent, so the 2nd lock will not block (its mutex is not yet locked).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?