Relative Content

Tag Archive for c#cmultithreadingvolatilememory-barriers

Deeply understanding Volatile and Memory Barriers

I have been reading a ton on this topic over the past view days but would really like clarification on what I learned so far in relations to C# and C. Firstly, Atomicity seems to be fairly intrinsic in modern times where I am strictly referring to the ability to read and write within a single instruction. It seems that C# always naturally aligns its data (which also seems to be done in C as well, but I heard there’s some cases this is not true). By alignment I mean that for example in x64 a long will be 8 bytes meaning its virtual memory address will be a multiple of 8. This way the CPU can read and write with its 8-byte wide BUS in a single cycle. If, however we were not aligned correctly and were off by a byte the CPU may require 2 cycles to read and write data which not only slows our program down it also removes atomicity since this could cause partial data to be observed. It’s also good to mention that this seems to also work for other data like a 4-byte int where that can also be read and written to within a single cycle also making it atomic. Lastly, this also seems to yield extra optimization where when doing something like reading an array we can now read / write 2 int’s at a time in our 8-byte wide BUS.