Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare and Swap on x86 - why is it a full barrier?

As per this question's answer, it seems that LOCK CMPXCHG on x86 actually causes a full barrier. Presumably, this is what Unsafe.compareAndSwapInt() generates under the hood as well. I am struggling to see why that is the case: with MESI protocol, after you updated the cache line, could the CPU simply invalidate just that cache line on other cores, rather than draining ALL store/load buffers of the core which performed CAS? Seems rather wasteful to me...

like image 288
Bober02 Avatar asked Jul 13 '17 12:07

Bober02


1 Answers

Your answer as far as I can see is in the comments - MESI updates caches, not Store/Load buffers. But lock LOCK CMPXCHG says: locked operations serialize all outstanding load and store operation - this is why it needs to drain the Store/Load buffer from this CPU (and not others as detailed here).

So the current CPU has to perform the atomic operation on the most recent value - that could reside in Store/Load buffers, that's why a fence is needed there to actually drain that.

like image 138
Eugene Avatar answered Sep 28 '22 10:09

Eugene