Assume we have a multithreaded C program (pthreads), and the (unsynchronized) shared variable accesses of the individual threads are not reordered by the compiler. Does an x86 CPU respect the order of the shared variable accesses (within a single thread), or is it possible that it reorders some memory accesses?
Assume we have a multithreaded C program (pthreads), and the (unsynchronized) shared variable accesses
Share
Unsynchronized shared variable accesses are dangerous, and out-of-order is one reason for it.
The x86 keeps writes in order (within a thread), but not reads.
This can get you into trouble, if you assume the order remains. For example:
Thread A writes to x and then to y. Assuming the compiler didn’t reorder it, the cpu won’t reorder it (x86 won’t, others might).
thread B reads y and then x. You might think that if it got y’s new value, then surely you’ll get x’s new value as well.
Not so. The CPU may reorder thread B’s reads, so y will be actually read earlier.
EDIT: as “Man of One Way” pointed out, in this case, x86 (but not all processors!) guarantees ordering.
I quote the Intel software developer’s manual:
This isn’t true for writes by multiple processors – they may seem to be ordered differently by different processors.
However, I highly recommend not relying on it, and using use proper synchronization instead.
The synchronization primitives are implemented with atomic operations and/or barriers, which keep you safe.