Cross-platform atomic exchange/compare exchange x86/x64

Share your advanced PureBasic knowledge/code with the community.
Mistrel
Addict
Addict
Posts: 3415
Joined: Sat Jun 30, 2007 8:04 pm

Cross-platform atomic exchange/compare exchange x86/x64

Post by Mistrel »

Frustrated with this problem here:
http://purebasic.fr/english/viewtopic.php?t=37782

I've compiled source code generously provided here for native cross-platform equivalents:
http://purebasic.fr/english/viewtopic.php?t=36939

Code: Select all

Procedure InterlockedExchange(*Destination.Integer, Value.i)
  CompilerIf #PB_Compiler_Processor=#PB_Processor_x86
    !mov ecx,[p.p_Destination]
    !mov eax,[p.v_Value]
    !xchg [ecx],eax
  CompilerEndIf
  CompilerIf #PB_Compiler_Processor=#PB_Processor_x64
    !mov rcx,[p.p_Destination]
    !mov rax,[p.v_Value]
    !xchg [rcx],rax
  CompilerEndIf
  ProcedureReturn
EndProcedure

Procedure InterlockedCompareExchange(*Destination.Integer, Exchange.i, Comparand.i)
  CompilerIf #PB_Compiler_Processor=#PB_Processor_x86
    !mov ecx,[p.p_Destination]
    !mov eax,[p.v_Comparand]
    !mov edx,[p.v_Exchange]
    !lock cmpxchg [ecx],edx 
  CompilerEndIf
  CompilerIf #PB_Compiler_Processor=#PB_Processor_x64
    !mov rcx,[p.p_Destination]
    !mov rax,[p.v_Comparand]
    !mov rdx,[p.v_Exchange]
    !lock cmpxchg [rcx],rdx
  CompilerEndIf
  ProcedureReturn
EndProcedure


InterlockedExchange(@This,2)
Debug This

InterlockedCompareExchange(@This,4,1)
Debug This
InterlockedCompareExchange(@This,4,2)
Debug This
XCHG is i286 and up and CMPXCHG is i486 and up, I believe.