3

I'm maintaining a high performance class that can be operated on by multiple threads. Many of the fields are volatile ints, and as it turns out I need to upgrade one of those to a double. I'm curious if there is a lock free way to do this, and was wondering if the Interlocked.CompareExchange(double, double, double) works as advertised on a 32-bit OS, or are torn reads a problem.

LukeH
  • 263,068
  • 57
  • 365
  • 409
Greg Graham
  • 473
  • 7
  • 18

3 Answers3

2

This page details the intrinsics of the "native" Interlocked functions. It mentions the following limitations

Because _InterlockedCompareExchange64 uses the cmpxchg8b instruction, it is not available on pre-Pentium processors, such as the 486.

So we can expect that it is available and also implemented as an interlocked instruction operation (rather than being simulated by using a full lock).

peterchen
  • 40,917
  • 20
  • 104
  • 186
1

Yes, it works as described on 32-bit. That's what the Interlocked methods are there for.

LukeH
  • 263,068
  • 57
  • 365
  • 409
0

Yes, it's works.

It uses InterlockedCompareExchange64 - if you want to have a look at a possible implementation in x86 asm, have a look here - http://qc.embarcadero.com/wc/qcmain.aspx?d=6212.

asm
//     ->          EAX     Destination 
//                 ESP+4   Exchange    
//                 ESP+12  Comperand   
//     <-          EDX:EAX Result      
          PUSH    EBX
          PUSH    EDI

          MOV     EDI, EAX

          MOV     EAX, DWORD PTR [Comperand]
          MOV     EDX, DWORD PTR [Comperand+4]

          MOV     EBX, DWORD PTR [Exchange]
          MOV     ECX, DWORD PTR [Exchange+4]

LOCK      CMPXCHG8B [EDI]

          POP     EDI
          POP     EBX
end;
Zach Saw
  • 4,308
  • 3
  • 33
  • 49
  • Note that [QualityCentral has now been shut down](https://community.embarcadero.com/blogs/entry/quality-keeps-moving-forward), so you can't access `qc.embarcadero.com` links anymore. If you need access to old QC data, look at [QCScraper](http://www.uweraabe.de/Blog/2017/06/09/how-to-save-qualitycentral/). – Remy Lebeau Jun 09 '17 at 17:33