How is the back lock under the hood?

This is a lock that can hold only one thread of execution at a time. An attempt to acquire a lock by another thread of execution last cycle until the lock is released.

How does it handle the case when two threads try to get a lock at exactly the same time ?

I think this question also applies to various mutex implementations.

+3
source share
2 answers

, , "", , ... .

x86 LOCK, , . , x86 .

  • ( , , ).
  • .
  • , . "" " ". , " ".

x86 , .

  • CMPXCHG. . :
uint32 cmpxchg(uint32 *memory_location, uint32 old_value, uint32 new_value) {
    atomically {
        if (*memory_location == old_value) 
            *memory_location = new_value;
        return old_value;
    }
}
  1. XCHG. :
uint32 xchg(uint32 *memory_location, uint32 new_value) {
    atomically {
        uint32 old_value = *memory_location;
        *memory_location = new_value;
        return *old_value;
    }
}

, :

uint32 mylock = 0;
while (cmpxchg(&mylock, 0, 1) != 0)
    ;

, , , -.

. , , , . , x86, , :

    Thread 1      Thread 2
    mov [w], 0    mov [x], 0
    mov [w], 1    mov [x], 2
    mov eax, w    mov eax, x
    mov [y], eax  mov [z], eax

y z 0!.

, : LOCK x86 ADD, OR AND, -- . , , , . :

   Thread 1       Thread 2
   AND [x], 0x1   AND [x], 0x2

x 1, 2 0x1 | 0x2 (3). , :

   Thread 1           Thread 2
   LOCK AND [x], 0x1  LOCK AND [x], 0x2

, .

+6

. , , , . , IA-32 xchg, . -, :

  eax = 1;
  while( xchg(eax, lock_address) != 0 );
  // now I have the lock
  ... code ...
  *lock_address = 0; // release the lock
+2

Source: https://habr.com/ru/post/1746752/


All Articles