You are here:

C++/is assigmnent for int atomic


i work in c++ using Visual Studio 2005.
I'd like to know of the assignment operation to int is atomic. If yes, can you show me proof for that?
It is the same in x64 OS?

ANSWER: Hi Dudi,

Yes, storing ints is atomic.  Generally, storing ints on a processor is atomic because int is the natural register size (or one of the sizes) and register stores are atomic.  This rule does not always hold for 8-bit processors.

You prove it by compiling to assembly language, or using the debugger to View Disassembly and seeing if the store takes one instruction.

For x64 OS, you mean 64-bit processor because the OS has no affect on atomic stores.  If x64 is running in 64-bit mode on the processor, then I would expect atomic stores.  The test above should be done to verify this as I have no x64 system.


---------- FOLLOW-UP ----------

QUESTION: But what about a system with multiple cores/cpus?
Suppose that the assignment is one instruction.
It is possible that during setting i to 0x123456 (writing to 4 bytes) another core/cpu will get half of the data (by having the situation that the first core wrote only 2 bytes of 4).

It doesn't matter about multiple cores/cpus - a word in memory has to be coherent between all processors when it is read and written in one CPU instruction.

No, it's not possible to split 0x123456 or any 4 bytes when the 4 bytes are written as one instruction because the instruction is atomic and cannot be interrupted.



All Answers

Answers by Expert:

Ask Experts


Bill A


I can answer questions about C++, programming algorithms, Windows programming in MFC (which is C++). I cannot answer questions about STL (templates) and I have no experience with Linux. I do enjoy reviewing code and critiquing it or finding problems in it. I will also gladly show better algorithms or methods if you want to take advantage of that.


I've developed a commercial embedded C compiler/assembler and IDE with debugger toolset, of which the IDE and debugger are written in C++. I work in the industry writing high tech embedded programs and Windows programs to communicate with the embedded devices.

Book: Embedded Systems Design using the Rabbit 3000 Microprocessor Authored Chapter 10 in its entirety.

BS Computer Engineering

©2017 All rights reserved.