When to use Test & Set or Test & Test & Set?

Concurrent programming under x86 can be difficult, especially on multi-core processors. Let's say that we have a multi-core x86 processor and more different combinations of multi-threaded communications.

  • Single writer and single reader
  • Several writers with one reader
  • Multiple readers and single writer
  • Several readers and several authors

So, which one model is better (more efficient) for locking the shared memory area: Test & Set or Test & Test & Set and when to use it!

Here I have two simple (no time limits) test procedures written in the Delphi IDE in x86 assembler:

procedure TestAndSet(const oldValue, newValue: cardinal; var destination);
asm
//eax = oldValue
//edx = NewLockValue
//ecx = destination = 32 bit pointer on lock variable 4 byte aligned
@RepeatSpinLoop:
        push    eax                   //Save lock oldValue (compared)
        pause                         //CPU spin-loop hint
        lock    cmpxchg dword ptr [ecx], edx
        pop     eax                   //Restore eax as oldValue
        jnz     @RepeatSpinLoop       //Repeat if cmpxchg wasn't successful
end;

procedure TestAndTestAndSet(const oldValue, newValue: cardinal; var destination);
asm
//eax = oldValue
//edx = NewLockValue
//ecx = destination = 32 bit pointer on lock variable 4 byte aligned
@RepeatSpinLoop:
        push    eax                   //Save lock oldValue (compared)
@SpinLoop:
        pause                         //CPU spin-loop hint
        cmp     dword ptr [ecx], eax  //Test betfore test&set
        jnz     @SpinLoop
        lock    cmpxchg dword ptr [ecx], edx
        pop     eax                   //Restore eax as oldValue
        jnz     @RepeatSpinLoop       //Repeat if cmpxchg wasn't successful
end;

EDIT:

Intel Test & Set Test & Test & Set. , - , , . : Intel

+3
3

TTAS (# 2) - . "Lurking" "" CAS Java, .NET . , cmpxchg , , .

, , , .

@GJ: Intel. , 486 xchg cmpxchg, , .

vs locked - , . (, TTAS.)

, , . , .

TTAS TAS , , L3 , - - - , . . (, TTAS/TAS.)

+2

, (testAndSet) , cmp jnz - . , , .

+3

2- , , , , :

  • SwitchToThread
  • SwitchToThread cmp
  • SwitchToThread cmp/lock

, , :

+2
source

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


All Articles