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


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 measured at)?

Is it even possible for two threads to execute instructions at the exact same concurrent time, or is that an impossibility with today's hardware?

Im working on a project that deals with muitithreading, where any thread may beat the other to the finish line, so to speak. So naturally, the question of "What happens when they all lock at the same time?" has to be addressed IMO.

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