tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

.NET types that can be read and written atomically without the risk of tearing

12 Dec 2016 2 mins .NET, .NET Core, Multithreading/Parallelism/Asynchronous/Concurrency

I’m currently digging deep into memory models, processor architectures, kernels and so on. It’s a fun stuff. I’m learning so much and my brain is working so hard. With that I’m also digging into some “concurrent” internals in .NET, in last few days the ConcurrentDictionary<TKey, TValue> class. As I was there I found something helpful.

Take a look here. It’s a list of types where tearing doesn’t happen. Of course unless misaligned manually. Awesome!

/// <summary>
/// Determines whether type TValue can be written atomically
/// </summary>
private static bool IsValueWriteAtomic()
{
    //
    // Section 12.6.6 of ECMA CLI explains which types can be read and written atomically without
    // the risk of tearing.
    //
    // See http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-335.pdf
    //
    Type valueType = typeof(TValue);
    bool isAtomic =
        !valueType.GetTypeInfo().IsValueType ||
        valueType == typeof(bool) ||
        valueType == typeof(char) ||
        valueType == typeof(byte) ||
        valueType == typeof(sbyte) ||
        valueType == typeof(short) ||
        valueType == typeof(ushort) ||
        valueType == typeof(int) ||
        valueType == typeof(uint) ||
        valueType == typeof(float);

    if (!isAtomic && IntPtr.Size == 8)
    {
        isAtomic =
            valueType == typeof(double) ||
            valueType == typeof(long) ||
            valueType == typeof(ulong);
    }

    return isAtomic;
}

Although I said it’s helpful, I don’t that mean anybody should rely on that. It’s good as brain training. Not for production level code. There’s a gazillion pieces that need to fit together to work correctly (platform, it’s memory model; compiler; JIT optimizations; …).

But for studying… Oh my.

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.