Recent

Author Topic: InterlockedCompareExchange  (Read 4880 times)

taazz

  • Hero Member
  • *****
  • Posts: 5368
InterlockedCompareExchange
« on: June 10, 2015, 04:52:34 am »
any one has any inside for the InterlockedCompareExchange function and when/how is used? From my naive point of view it seems a bit unnecessary eg what is the point in comparing newvalue to comperand and then setting the target to it? when is this going to be needed?
Good judgement is the result of experience … Experience is the result of bad judgement.

OS : Windows 7 64 bit
Laz: Lazarus 1.4.4 FPC 2.6.4 i386-win32-win32/win64

rtusrghsdfhsfdhsdfhsfdhs

  • Full Member
  • ***
  • Posts: 162
Re: InterlockedCompareExchange
« Reply #1 on: June 10, 2015, 06:39:53 am »
It is used for lock free structures such as queues etc..

DonAlfredo

  • Hero Member
  • *****
  • Posts: 1862
Re: InterlockedCompareExchange
« Reply #2 on: June 10, 2015, 07:23:39 am »
I use (Delphi code)
Code: [Select]
if TInterlocked.Exchange(TimersBusy, integer(True))<>integer(True) then
begin
    try
      // do something time-consuming
    finally
      TInterlocked.Exchange(TimersBusy, integer(False));
    end;
end;
a lot in timer code to prevent re-entrant-errors

taazz

  • Hero Member
  • *****
  • Posts: 5368
Re: InterlockedCompareExchange
« Reply #3 on: June 10, 2015, 07:50:17 am »
I do understand some of the use cases for InterlockedExchange, I'm guessing that there are far more than I can see for now, but I can't understand the compare part. I'm used in ranged compares for values eg case, between etc but I can't see a use case where I would like to set a value only when it is equal to X where X is very specific ee not a range or something different than the new value. Lets simplify things a bit so we can talk on the same think if I was to re-create those two functions using critical sections for example it would go something along the lines of
Code: [Select]
function InterLockedExchange(var Target: Pointer;Source: Pointer):Pointer;
begin
  EnterCriticalSection(myCS);
  try
    result := target;
    target := Source;
  finally
    LeaveCriticalSection(myCS);
  end;
end;
function InterlockedCompareExchange(var Target: Pointer;  NewValue: Pointer;  Comperand: Pointer):Pointer;
begin
  EnterCriticalSection(myCS);
  try
    Result := target;
    if NewValue = Comperand then target := NewValue;
  finally
    LeaveCriticalSection(myCS);
  end;
end;

and that makes no sense to me at all. Any cases I could take a look? For now is categorized as "nice idea no real value".
Good judgement is the result of experience … Experience is the result of bad judgement.

OS : Windows 7 64 bit
Laz: Lazarus 1.4.4 FPC 2.6.4 i386-win32-win32/win64

DonAlfredo

  • Hero Member
  • *****
  • Posts: 1862
Re: InterlockedCompareExchange
« Reply #4 on: June 10, 2015, 08:14:29 am »
AFAIK, CS-locks are (much) more expensive than a simple InterLocked[Compare]Exchange.

 

TinyPortal © 2005-2018