What happens when two threads ATTEMPT to lock the same resource at the exact same time?

房东的猫 提交于 2019-12-01 06:52:00

Modern locks, in pretty much all environments, are designed such that it isn't possible for two threads to lock an object at the same time. It is possible for modern processors to have two threads running on two different cores attempt to take a lock at very nearly the same time, but they all implement synchronization mechanisms that allow software to tell them not to allow it.

For example, x86-64 has MONITOR and MWAIT instructions. They essentially implement, at the microprocessor level, the semantics of .NET's lock(){}, System.Threading.Monitor.Wait() and System.Threading.Monitor.Enter()/.Exit().

This isn't possible, locks couldn't do what they promise. This requires processor support since it is the only one that can ensure that multiple cores don't try to access the same memory location at the same time. An example is this bit of assembly code, used by the x86 version of the CLR in its Monitor.TryEnter() method:

FASTCALL_FUNC CompareExchangeUP,12
        _ASSERT_ALIGNED_4_X86 ecx
        mov     eax, [esp+4]    ; Comparand
        cmpxchg [ecx], edx
        retn    4               ; result in EAX
FASTCALL_ENDFUNC CompareExchangeUP

The cmpxchg processor instruction provides the atomicity guarantee. It is the kind of instruction that any modern core has, the generic name for it is "compare-and-swap". You'll find more about this instruction in this Wikipedia article.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!