NuGet Version and Downloads count Actions Status Codacy Badge CodeFactor

    Hardware.Cpu

    LinksPlatform's Platform.Hardware.Cpu Class Library.

    Namespace: Platform.Hardware.Cpu

    Forked from: NickStrupat/CacheLineSize.NET

    NuGet package: Platform.Hardware.Cpu

    Example

    using System;
    using Platform.Hardware.Cpu;
    
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(CacheLine.Size); // Print the cache line size in bytes
            
            var array = new CacheLineAlignedArray<string>(10);
            Interlocked.Exchange(ref array[0], "Hello"); // All threads can now see the latest value at `array[0]` without risk of ruining performance with false-sharing
    
            // This can be used to build collections which share elements across threads at the fastest possible synchronization.
        }
        
        // An array-like type where each element is on it's own cache-line. This is a building block for avoiding false-sharing.
        public struct CacheLineAlignedArray<T>
            where T : class
        {
            private readonly T[] buffer;
            public CacheLineAlignedArray(Int32 size) => buffer = new T[Multiplier * size];
            public Int32 Length => buffer.Length / Multiplier;
            public ref T this[Int32 index] => ref buffer[Multiplier * index];
            private static readonly Int32 Multiplier = CacheLine.Size / IntPtr.Size;
        }
    }
    

    Documentation

    PDF file with code for e-readers.

    Dependent libraries

    • Platform.Unsafe

    See also

    • NickStrupat/CacheLineSize.NET for the equivalent .NET Standard 1.5 library (without .NET Framework support)
    • NickStrupat/CacheLineSize for the equivalent C function
    • ulipollo/CacheLineSizeMex for the MATLAB function
    • Improve this Doc
    Back to top Generated by DocFX