Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Interlocked.Xxx methods guarantee value updated in all data caches?

Example:

Thread a:  Interlocked.Increment(ref x);

Thread b:  int currentValue = x;

Assuming thread b executes after thread a, is "currentValue" in thread b guaranteed to be the incremented value? Or, does thread b need to do a Thread.VolatileRead(ref x)?

like image 221
noctonura Avatar asked Dec 12 '12 23:12

noctonura


1 Answers

Technically that depends on the CPU .NET is running on, but for any common CPU the answer is yes, cache coherency is guaranteed for an Interlocked.Increment. It acts as a memory barrier as required by MESI.

a CPU can have in its cache a line which is invalid, but where it doesn't yet know that line is invalid - the invalidation queue contains the invalidation which hasn't yet been acted upon. (The invalidation queue is on the other "side" of the cache; the CPU can't scan it, as it can the store buffer). As a result, memory barriers are required.

http://en.wikipedia.org/wiki/MESI_protocol (x86)

MOESI (used on AMD64 chips) is quite similar:

http://en.wikipedia.org/wiki/MOESI_protocol (AMD64)

like image 111
Eric J. Avatar answered Oct 30 '22 19:10

Eric J.