Somewhere, one time I read about memory fences (barriers). It was said that memory fence causes cache synchronisation between several CPU cores.
So my questions are:
How does the OS (or CPU itself) know which cores need to be synchronised?
Does it synchronise cache of all CPU cores?
If answer to (2) is 'yes' and assuming that sync operations are not cheap, does using memory fences slow down cores that are not used by my application? If for example I have a single threaded app running on my 8-core CPU, will it slow down all other 7 cores of the CPU, because some cache lines must be synced with all those cores?
Are the questions above totally ignorant and fences work completely differently?
Generally, memory fences are used for ordering local operations. Take for instance this pseudo-assembler code:
load A
load B
Many CPU's do not guarantee that B is indeed loaded after A, B may be in a cache line that was loaded into cache earlier due to some other memory load. If you introduce a fence,
load A
readFence
load B
you have the guarantee that B is loaded from memory after A is. If B were in cache but older than A, it would be reloaded.
The situation with stores is the same the other way around. With
store A
store B
some CPUs may decide to write B to memory before they write A. Again, a fence between the two instructions may be needed to enforce ordering of the operations. Whether a memory fence is required always depends on the architecture.
Generally, you use memory fences in pairs:
If one thread wants to publish an object, it first constructs the object, then it performs a write fence before it writes the pointer to the object into a publicly known location.
The thread that wants to receive the object, reads the pointer from the publicly know memory location, then it executes a read fence to ensure that all further reads based on that pointer actually give the values the publishing thread intended.
If either fence is missing, the reader may read the value of one or more data members of the object before it was initialized. Madness ensues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With