Does Interlocked.CompareExchange use a memory barrier?

Any x86 instruction that has lock prefix has full memory barrier. As shown Abel’s answer, Interlocked* APIs and CompareExchanges use lock-prefixed instruction such as lock cmpxchg. So, it implies memory fence. Yes, Interlocked.CompareExchange uses a memory barrier. Why? Because x86 processors did so. From Intel’s Volume 3A: System Programming Guide Part 1, Section 7.1.2.2: For … Read more

How to stop / freeze / pause volatile RAND / RANDBETWEEN / RANDARRAY?

first, let’s see what says the fox =WHATTHEFOXSAY() is a unique easter egg google sheets function (discovered by @kishkin) that randomly generates a pre-set string of text on user demand which is a huge deal because while the generation is random, the recalculation is not affected by onEdit, onChange nor onOpen events, so with some … Read more

Volatile variable in Java

Declaring a volatile Java variable means: The value of this variable will never be cached thread-locally: all reads and writes will go straight to “main memory”. Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself. Just for your reference, When is volatile needed ? When multiple threads … Read more

Volatile in C++11

Whether it is optimized out depends entirely on compilers and what they choose to optimize away. The C++98/03 memory model does not recognize the possibility that x could change between the setting of it and the retrieval of the value. The C++11 memory model does recognize that x could be changed. However, it doesn’t care. … Read more

Happens-before relationships with volatile fields and synchronized blocks in Java – and their impact on non-volatile variables?

Yes, it is guaranteed that thread 2 will print “done” . Of course, that is if the write to b in Thread 1 actually happens before the read from b in Thread 2, rather than happening at the same time, or earlier! The heart of the reasoning here is the happens-before relationship. Multithreaded program executions … Read more

Why does volatile exist?

volatile is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to. I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially … Read more