Memory Ordering, Out of other Execution and Multi thread Safety

80 Views Asked by At

I have been reading on memory re-ordering lately. My question is with regarding to multi threading scenarios. Consider the example below:

A = 0;
B = 0;

Thread 1 on Processor 1                       Thread 2 on Processor 2

    A = 100;                                      while(B== 0);
    B = 1;                                       //access A here

I have been coding on X86-64 windows platforms and never considered that stores to A and B could be reordered (either at compiler level or at hardware level) and I may end up with B = 0 in thread 2 and find A to be still 0. And never ran into any issues or pesky bugs with such a code. Is it because x86-x64 are strongly ordered and so are windows C compilers.

For such a code to be executing on any other platform with weakly ordered memory, do I need to make sure I update and access A and B within a lock (assuming the underlying lock implementation uses memory barriers and make sures the lock is released only after all the prior loads and stores are visible across all processor cores).

Thanks

1

There are 1 best solutions below

4
On

Is it because x86-x64 are strongly ordered and so are windows C compilers.

Indeed, X86 is a strongly ordered CPU that does not allow store reordering. So all CPU cores will observe the order emitted by the compiler.

However, B is modified on processor 1, while read on processor 2. That is not allowed by the C memory model without synchronization (try maximum compiler optimization, it may stop working).

Although locking can be used to synchronize between cores, it may be problematic since your are spinning on B. If that happens with the lock acquired, processor 1 can not update the value.

A correct solution is to make B atomic. That will guarantee correct ordering on all levels.