/* * License Information * * Copyright (C) 2010 Jeroen Frijters * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * This code may only be studied and used for experimental purposes. * */ using System; using System.Threading; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Reflection; static class __Hack__DoNotUse { /* --- IMPORTANT NOTICE --- * * This code is NOT SAFE to use in production. * * Patching instructions like this is not "thread" safe. * */ static __Hack__DoNotUse() { byte[] code = { 0x53, // push ebx 0x90, // nop 0x8B, 0x5C, 0x24, 0x04, // mov ebx,dword ptr [esp+4] 0xB8, 0x0F, 0xAE, 0xF0, 0xB0, // mov eax,B0F0AE0Fh 0xF0, 0x87, 0x43, 0xFB, // lock xchg eax,dword ptr [ebx-5] 0x5B, // pop ebx 0xC3 // ret }; if (IntPtr.Size == 8) { code[1] = 0x48; // rex.w code[5] = 0x08; // mov rbx,qword ptr [esp+8] } RuntimeMethodHandle method = ((ThreadStart)MemoryBarrier).Method.MethodHandle; RuntimeHelpers.PrepareMethod(method); IntPtr p = method.GetFunctionPointer(); Marshal.Copy(code, 0, p, code.Length); } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] public static void MemoryBarrier() { // reserve some space to overwrite MemoryBarrier(); MemoryBarrier(); MemoryBarrier(); MemoryBarrier(); MemoryBarrier(); MemoryBarrier(); MemoryBarrier(); MemoryBarrier(); } } class Program { static volatile int foo; static void Main(string[] args) { for (; ; ) { Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i < 100000000; i++) { foo = 0; __Hack__DoNotUse.MemoryBarrier(); //Thread.MemoryBarrier(); } sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); } } }