William
William

Reputation: 1895

Are atomic operations always preformed sequentially within the same CPU cycle?

If I have some simple non-atomic code like so:

a++;

which can be broken down to machine instructions like so:

MOV EAX, [a]
INC EAX
MOV [a], EAX

I'm not familiar with machine code, please excuse me if that is incorrect, but basically assume that they are preformed atomically

Am I right in thinking that the CPU could preform the first action, then run numerous cycles, then do the next action, more cycles, then finally the last part of the machine code?

As apposed to preforming each bit of machine code sequentially to each other with-in the same cycle.

Upvotes: 2

Views: 483

Answers (2)

mattnewport
mattnewport

Reputation: 14077

On modern x86/x64 processors you can't even assume that a single architectural instruction maps to a single CPU (machine) instruction. Modern CPUs generally implement x86/x64 instructions internally as a series of architecture specific microcode instructions. The order these are executed in doesn't map in any simple way to the order they appear in in your executable due to out of order execution, speculative execution, etc. There is also no simple mapping between CPU clock cycles and number of instructions executed.

On top of this, with multithreaded code your thread may be context switched at any time so there can be arbitrarily long delays with arbitrary other operations occurring between any two instructions being executed.

The only way to get logical atomicity in a modern multithreaded envrionment is to use the appropriate atomic and synchronization instructions provided by the architecture which guarantee atomic behavior not just at the instruction level but across the memory hierarchy (L1, L2, L3 cache and main memory, plus store buffers etc.).

Upvotes: 4

James
James

Reputation: 4716

Most CPUs found in computers since the Pentium have indeed used out of order execution. This is a very complex process by which high level instructions are first decomposed into very small operations, then put into an execution queue where instructions are executed in the order in which input operands become available. You might read a more detailed description on Wikipedia.

Upvotes: 2

Related Questions