private static long* misalignedLongPtr = GetMisalignedHeapLong();
private static long* GetMisalignedHeapLong() {
const int MISALIGNMENT = -3;
const int X64_CACHE_LINE_SIZE = 64;
const int WIN_ALLOC_ALIGN = 8;
IntPtr reservedMemory = Marshal.AllocHGlobal(new IntPtr(sizeof(long) + X64_CACHE_LINE_SIZE + (sizeof(long) - 1) + WIN_ALLOC_ALIGN));
IntPtr cacheLineStart = (IntPtr) ((((long) reservedMemory + (X64_CACHE_LINE_SIZE - 1)) / X64_CACHE_LINE_SIZE) * X64_CACHE_LINE_SIZE);
return (long*) (cacheLineStart + MISALIGNMENT);
}
private static void WriterThreadEntry() {
while (true) {
*misalignedLongPtr = -1L;
*misalignedLongPtr = 1L;
}
}
private static void ReaderThreadEntry() {
while (true) {
var value = *misalignedLongPtr;
if (value != 1L && value != -1L) {
Console.WriteLine("Torn read! " + value);
}
}
}
Code snippet taken from "Common Multithreading Mistakes in C# - IV: Everything Else".