Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when two threads ATTEMPT to lock the same resource at the exact 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.

like image 812
Martin Bliss Avatar asked Dec 27 '22 20:12

Martin Bliss


1 Answers

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.

like image 153
Hans Passant Avatar answered Apr 19 '23 21:04

Hans Passant