Locking on field or local variable?

后端 未结 5 573
猫巷女王i
猫巷女王i 2021-01-17 23:18

After I read this question with an answer from Marc....

I sometimes see people locking on a local variable.

Is this code broken?

         


        
5条回答
  •  自闭症患者
    2021-01-17 23:52

    I believe object o = new Object(); should be outside the method as a Field.

    Since each thread is getting a new instance of o, there will be multiple locks.

    What am I missing here? Shouldn't it lock on fields in this specific case?

    Your understanding is correct. The code is broken. In this implementation even though lock will be active, it will not provide synchronization as it will be on different objects.

    From Microsoft Docs

    When you synchronize thread access to a shared resource, lock on a dedicated object instance (for example, private readonly object balanceLock = new object();) or another instance that is unlikely to be used as a lock object by unrelated parts of the code. Avoid using the same lock object instance for different shared resources, as it might result in deadlock or lock contention. In particular, avoid using the following as lock objects:

    this, as it might be used by the callers as a lock. Type instances, as those might be obtained by the typeof operator or reflection. string instances, including string literals, as those might be interned. Hold a lock for as short time as possible to reduce lock contention.

提交回复
热议问题