Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will CPU cache line flush after Compare and Swap?

suppose there are two variables store in the same CPU cache line, if I succesfully CAS one of the variable, will the whole cache line be update immediately after CAS instruction?

like image 271
user3526999 Avatar asked Sep 02 '25 02:09

user3526999


2 Answers

Yes, it is a full memory barrier across that cache line, and whatever your operation is does affect the entire cache line, however, you should be careful on what your expectation is when you start talking about the cache line in relation to variables.


Put another way, you can do a an atomic operation, like CAS, and the cache line will be updated immediately. It is a full-memory barrier, so any pending memory operations would be resolved before the effect of the atomic. It doesn't affect variables in any way, as those have nothing to do with the cache line, however, if you later fetch that cache line, either through a CAS or a memory operation, you would see the result of your prior CAS operation.

like image 160
Clarus Avatar answered Sep 07 '25 14:09

Clarus


It doesn't have to update, it's already updated. Cache visibility (on normal systems and memory types) guarantees that any cache line read with normal operations wields the same result as if the entire memory was flat and updated consistently. If, on the other hand, you're dealing with partial, WC, streaming, or any other not-necessarily-coherent access then you don't get that guarantee.

With locked operations, this is usually achieved in hardware by grabbing an internal lock over the cache line, so that the CAS is performed atomically (read-modify-write), but this is orthogonal to cache coherency. Regardless of the operation you performed (even on a simple store), any read operation hitting that cache line immediately "after" (either younger in program order on the same thread, or chronologically afterwards on any other thread/core) would see the line after the CAS operation. Of course, accesses from other threads may also snoop the line before that operation and see the old data (depending on your system memory ordering and any precautions your code takes).

like image 27
Leeor Avatar answered Sep 07 '25 14:09

Leeor