Should Interlocked.CompareExchange also a volatile variable?

No, volatile wouldn’t be helpful at all, and certainly not for this reason. It would just give that first read “acquire” semantics instead of effectively relaxed, but either way will compile to similar asm that runs a load instruction. if you get a dirty value from a CPU cache CPU caches are coherent, so anything … Read more

What kinds of optimizations does ‘volatile’ prevent in C++?

Basically, volatile announces that a value might change behind your program’s back. That prevents compilers from caching the value (in a CPU register) and from optimizing away accesses to that value when they seem unnecessary from the POV of your program. What should trigger usage of volatile is when a value changes despite the fact … Read more

Why does std::cout convert volatile pointers to bool?

Up through the C++20 standard, ostream::operator<< has the following overloads, among others: ostream& operator<< (bool val ); ostream& operator<< (const void* val ); When you pass in a volatile pointer, the second overload can’t apply because volatile pointers cannot be converted to non-volatile without an explicit cast. However, any pointer can be converted to bool, … Read more

Working of __asm__ __volatile__ (“” : : : “memory”)

asm volatile(“” ::: “memory”); creates a compiler level memory barrier forcing optimizer to not re-order memory accesses across the barrier. For example, if you need to access some address in a specific order (probably because that memory area is actually backed by a different device rather than a memory) you need to be able tell … Read more

How do I Understand Read Memory Barriers and Volatile

There are read barriers and write barriers; acquire barriers and release barriers. And more (io vs memory, etc). The barriers are not there to control “latest” value or “freshness” of the values. They are there to control the relative ordering of memory accesses. Write barriers control the order of writes. Because writes to memory are … Read more

Volatile Vs Atomic [duplicate]

The effect of the volatile keyword is approximately that each individual read or write operation on that variable is made atomically visible to all threads. Notably, however, an operation that requires more than one read/write — such as i++, which is equivalent to i = i + 1, which does one read and one write … Read more