Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

file 286 lines (235 sloc) 8.081 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;


namespace ConcurrentList
{
  public class ConcurrentList<T> : IList<T>
  {
    private int _nextIndex;
    private int _count;
    
    static readonly int[] Sizes;
    static readonly int[] Counts;
    const int NUM_BUCKETS = 29;
    const int FIRST_SIZE = 8;


    static ConcurrentList()
    {
      Sizes = new int[NUM_BUCKETS];
      Counts = new int[NUM_BUCKETS];

      Sizes[0] = FIRST_SIZE;
      Counts[0] = FIRST_SIZE;

      for (int i = 1; i < NUM_BUCKETS; i++)
      {
        Sizes[i] = Sizes[i - 1] << 1;
        Counts[i] = Counts[i - 1] + Sizes[i];
      }
    }

    private readonly T[][] _array;

    public ConcurrentList()
    {
      _array = new T[NUM_BUCKETS][];
    }

    private const short SPIN_COUNT = 100;

    public T this[int index]
    {
      get {
        if (index < 0 || index >= _count)
          throw new ArgumentOutOfRangeException("index");

        var arrayIndex = GetArrayIndex(index);
        if (arrayIndex > 0)
          index -= Counts[arrayIndex - 1];

        return _array[arrayIndex][index];
      }
      set {
        if (index < 0 || index >= _count)
          throw new ArgumentOutOfRangeException("index");

        var arrayIndex = GetArrayIndex(index);
        if (arrayIndex > 0)
          index -= Counts[arrayIndex - 1];

        _array[arrayIndex][index] = value;
      }
    }



    public void Clear()
    {
      //long expectedLong;
      var spinCount = 0;

      var frozenNext = Interlocked.Exchange(ref _nextIndex, 0);
      //expectedLong = ((long) frozenNext << 32) | frozenNext;
      while (Interlocked.CompareExchange(ref _count, 0, frozenNext) != frozenNext)
        if (++spinCount == SPIN_COUNT)
        {
          // Someone is doing insane number of concurrent additions for us to be
          // stuck so far..., better go sleep for a while to let some other threads progress
          Thread.Sleep(0);
          spinCount = 0;
        }

    }

#if HELL_FROZE_OVER
    public void ClearX()
    {
      var frozenNext = Interlocked.Exchange(ref _nextIndex, 0);
    start_clear:
      var spinCount = 0;
      while (_count != frozenNext)
        if (++spinCount == SPIN_COUNT) {
          // Someone is doing insane number of concurrent additions for us to be
          // stuck so far..., better go sleep for a while to let some other threads progress
          Thread.Sleep(0);
          spinCount = 0;
        }
      Thread.MemoryBarrier();
      //Interlocked.Exchange(ref _fuzzyCount, index + 1);
      if (Interlocked.CompareExchange(ref _count, 0, frozenNext) == frozenNext)
        return;

      goto start_clear;
    }
#endif

    public int Count
    {
      get { return _count; }
    }

    public unsafe void Add(T element)
    {
      // This is rougly translated on x64 to (which is sub-optimal, but whatever):
      // mov eax,1
      // lock xadd dword ptr [rsi+10h],eax
      // inc eax
      // lea ebp,[rax-1]
      // mov r13d,ebp


      var index = Interlocked.Increment(ref _nextIndex) - 1;
      var adjustedIndex = index;

      var arrayIndex = GetArrayIndex(adjustedIndex);

#if HELL_FROZE_OVER
      var prevCount = 0;
      if (arrayIndex > 0)
        prevCount = Counts[arrayIndex - 1];
      if (index < prevCount || index >= Counts[arrayIndex])
        throw new Exception("Booboo");
#endif

      if (arrayIndex > 0)
        adjustedIndex -= Counts[arrayIndex - 1];

      if (_array[arrayIndex] == null) {
        int arrayLength = Sizes[arrayIndex];
        // Unfortunately this is some obscure call to COMInterlocked::CompareExchangeObject, which we shouldn't care
        // about too much since it's not really in the critical path
        // lea r8,[mscorlib_ni+0x1ad2 (000007fe`dc0e1ad2)]
        // call clr!JIT_Ldelema_Ref (000007fe`efeca2e0)
        // mov rdi,rax
        // movsxd rdx,ebx
        // lea rcx,[mscorlib_ni+0x1ad2 (000007fe`dc0e1ad2)]
        // call clr!JIT_NewArr1VC_MP_InlineGetThread (000007fe`efe72f90)
        // xor r8d,r8d
        // mov rdx,rax
        // mov rcx,rdi
        // call clr!COMInterlocked::CompareExchangeObject (000007fe`efeb3b30)
        Interlocked.CompareExchange(ref _array[arrayIndex], new T[arrayLength], null);
      }

      _array[arrayIndex][adjustedIndex] = element;

      // Do a "smart" spin loop, try spinning for a while waiting for the _fuzzyCount to hit the right value
      // After a while, try sleeping a bit,
      // once it hits the right value, do a compare and exchange, although it is somewhat superflous at this point
      //
      var spinCount = 0;

#if HELL_FROZE_OVER
      while (_count != index)
        if (++spinCount == SPIN_COUNT) {
          // Someone is doing insane number of concurrent additions for us to be
          // stuck so far..., better go sleep for a while to let some other threads progress
          Thread.Sleep(0);
          spinCount = 0;
        }

      if (Interlocked.CompareExchange(ref _count, index + 1, index) == index)
        return;

      throw new Exception("WTF");
#endif
      // This is rougly translated on x64 to::
      // lea ebx,[rbp+1]
      // mov eax,ebp
      // lock cmpxchg dword ptr [rsi+14h],ebx
      // cmp eax,ebp
      while (Interlocked.CompareExchange(ref _count, index + 1, index) != index) {
        if (++spinCount != SPIN_COUNT) continue;
        // Someone is doing insane number of concurrent additions for us to be
        // stuck so far..., better go sleep for a while to let some other threads progress
        Thread.Sleep(0);
        spinCount = 0;
      }
    }

    public bool Contains(T element)
    {
      return IndexOf(element) != -1;
    }

    public int IndexOf(T element)
    {
      IEqualityComparer<T> equalityComparer = EqualityComparer<T>.Default;

      int count = Count;
      for (int i = 0; i < count; i++)
      {
        if (equalityComparer.Equals(this[i], element))
        {
          return i;
        }
      }

      return -1;
    }

    public void CopyTo(T[] array, int index)
    {
      if (array == null)
      {
        throw new ArgumentNullException("array");
      }

      var count = Count;
      if (array.Length - index < count)
      {
        throw new ArgumentException("There is not enough available space in the destination array.");
      }

      var arrayIndex = 0;
      var elementsRemaining = count;
      while (elementsRemaining > 0)
      {
        var source = _array[arrayIndex++];
        var elementsToCopy = Math.Min(source.Length, elementsRemaining);
        var startIndex = count - elementsRemaining;

        Array.Copy(source, 0, array, startIndex, elementsToCopy);

        elementsRemaining -= elementsToCopy;
      }
    }

    public IEnumerator<T> GetEnumerator()
    {
      var count = Count;
      var ai = 0;
      while (count > 0)
      {
        var ar = _array[ai++];
        var lastElem = Math.Min(count, ar.Length);
        for (var j = 0; j < lastElem; j++)
          yield return ar[j];
        count -= ar.Length;
      }
    }

    private static int GetArrayIndex(int index)
    {
      return LOG2Hack.Log2(index / FIRST_SIZE + 1);
    }

    void IList<T>.Insert(int index, T element)
    {
      throw new NotSupportedException();
    }

    void IList<T>.RemoveAt(int index)
    {
      throw new NotSupportedException();
    }

    bool ICollection<T>.IsReadOnly
    {
      get { return false; }
    }

    bool ICollection<T>.Remove(T element)
    {
      throw new NotSupportedException();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
      return GetEnumerator();
    }
  }
}
Something went wrong with that request. Please try again.