0

Suppose we have a 64-bit global variable, initially zero.

volatile uint64_t gDest = 0;

Store (Atomic) – in one thread. At some point, we atomically increment a 64-bit value of this variable.

AtomicIncrement64 (&gDest); 

Here AtomicIncrement64 - can be one of compiler intrinsics or builtins like InterlockedIncrement64 (cl) and __sync_add_and_fetch(GCC)

Load – in another thread

uint64_t a = gDest;

Here if compiler might have implemented the load operation using two machine instructions: The first reads the lower 32 bits into eax, and the second reads the upper 32 bits into edx. In this case, if a concurrent atomic store to gDest becomes visible between the two instructions, will it result in torn read?

Abhishek Jain
  • 9,614
  • 5
  • 26
  • 40
  • It simply can't. (At least on machines running > Windows 2000.) The InterlockedIncrement() translates to a **locked** instruction, so you can't read the memory while it is being written. Never. Not under any circumstances. – mg30rg Jun 03 '15 at 11:22
  • By locked, you mean a memory barrier? – Abhishek Jain Jun 03 '15 at 12:02
  • Since I'm no expert in processor architectures, I'm not sure about the proper term. What I know is that `Interlocked*()` translates to an instruction with the `lock` prefix which ensures that the CPU has exclusive ownership of the appropriate cache line for the duration of the operation, and provides certain additional ordering guarantees. I'm not sure _how_ it is realized, but it works like it. – mg30rg Jun 03 '15 at 12:33
  • Some further research have led me to [this](http://stackoverflow.com/a/3339380/2144232) answer where you can find details on how `lock` locks the memory. – mg30rg Jun 03 '15 at 12:37
  • What would be the point of atomics if they weren't atomic? – harold Jun 04 '15 at 07:23
  • concurrent atomic operations can still lead to torn reads but the question is the APIs and builtins in discusion, do more than making the operation atomic. see this article: http://preshing.com/20130618/atomic-vs-non-atomic-operations/. – Abhishek Jain Jun 04 '15 at 10:55
  • Now hold on, why would you even use 64bit atomics on a 32bit platform? That doesn't make any sense. – harold Jun 04 '15 at 16:18
  • In my 32 bit application running on x86, can't I use a 64 bit integer which needs to be atomically incremented? – Abhishek Jain Jun 05 '15 at 04:25
  • Maybe, but there won't be an atomic increment instruction, so it would have to be some annoyingly complicated piece of code. Even if the compiler generates it (does it? I'd hope it would. But perhaps only if you don't mix atomics with normal access), it probably won't be as fast as you'd like. – harold Jun 05 '15 at 07:26

0 Answers0