3 ms·
But you'll need memory barriers. Let's say you have two variables, x and y, satisfying x >= y at all times, and the values of x and y are never allowed to decr
by klodolph 13y ago
But you'll need memory barriers. Let's say you have two variables, x and y, satisfying x >= y at all times, and the values of x and y are never allowed to decrease.
// Thread 1
atomic_inc(&x);
atomic_inc(&y);
// Thread 2
local_y = atomic_read(&y);
local_x = atomic_read(&x);
If you go through it logically, it's always in a valid state, right?
No. You need explicit synchronization. If we start at x=1, y=1, then thread 2 can see x=1, y=2, which seems impossible!
Or in short, your exception sucks. (By "sucks" I mean it is not sufficiently detailed enough to prevent errors.)
- rayiner 13y agoThis is only the case on architectures where atomic operations don't imply memory barriers. On x86, there is a total order on atomic operations, do another CPU will never see the write to "y" before the write to "x". Indeed on x86, there is total order on stores, so if you had two threads like that, where one thread only did reads and the other thread did updates, you can get away with an unlocked increment (x++; y++).