128 bit/16 byte Interlocked.CompareExchange with structs
Use cases
- Lock free algorithms using tagged state reference rather than GC (for ABA problem)
- Atomic update for 16 byte structs on heap (e.g.
Span<T>, Vector4)
Availability
- Always - Windows 8.1 x64 (Required)
- Always - Windows 10 x64 (Required)
- Always - OSX/MacOS (Intel)
- Usually - Linux x64
- Usually - Windows 7 x64
Performance
- Not fast, but generally less than double a 8 byte LOCK CMPXCHG
Issues
- No 32 bit available (I believe?)
- Not available on some early AMD x64 (pre-2006)
- Alternative may not be available for ARM and other CPUs
- Data needs to be 16 byte aligned
Questions
Seems a bit heavyweight for general case of 16 byte struct copy (e.g. Vector4)
Would prevent tearing when coherence is required, though slow (e.g. heap based Span<T>)
But both tagged state reference and Span<T> would have a similar data format, so also contain references.
| 64 bits |
64 bits |
| Reference |
Data |
Would require the heap struct to have an alignment (16 bytes), would need to be first class structs for passing.
Attribute?
Compile time enforcement?
Api
namespace System.Threading
{
public interface IAlignedAnd16Bytes { }
public static class Interlocked
{
public static T CompareExchange<T>(ref T location1, T value, T comparand)
where T : struct, IAlignedAnd16Bytes;
}
}
Struct would need to be TYP_STRUCT16?
InterlockedCompareExchange128 https://msdn.microsoft.com/en-us/library/windows/desktop/hh972640%28v=vs.85%29.aspx
/cc @CarolEidt @mikedn @jaredpar @jkotas @stephentoub
128 bit/16 byte Interlocked.CompareExchange with structs
Use cases
Span<T>,Vector4)Availability
Performance
Issues
Questions
Seems a bit heavyweight for general case of 16 byte struct copy (e.g.
Vector4)Would prevent tearing when coherence is required, though slow (e.g. heap based
Span<T>)But both tagged state reference and
Span<T>would have a similar data format, so also contain references.Would require the heap struct to have an alignment (16 bytes), would need to be first class structs for passing.
Attribute?
Compile time enforcement?
Api
Struct would need to be TYP_STRUCT16?
InterlockedCompareExchange128 https://msdn.microsoft.com/en-us/library/windows/desktop/hh972640%28v=vs.85%29.aspx
/cc @CarolEidt @mikedn @jaredpar @jkotas @stephentoub