Skip to content

Latest commit

 

History

History
55 lines (42 loc) · 2.9 KB

README.md

File metadata and controls

55 lines (42 loc) · 2.9 KB

NuGet Version and Downloads count Actions Status Codacy Badge CodeFactor

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;
    }
}

PDF file with code for e-readers.

Dependent libraries

See also