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).

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

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。