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

后端 未结 2 1927
滥情空心
滥情空心 2021-01-13 23:48

What happens when two threads attempt to lock the same object at the exact same microsecond (or whatever is the smallest length of time a CPU slice or instruction can be mea

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-14 00:33

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

提交回复
热议问题