SplitOrderedList.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. // SplitOrderedList.cs
  2. //
  3. // Copyright (c) 2010 Jérémie "Garuma" Laval
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. //
  24. #if NET_4_0 || BOOTSTRAP_NET_4_0 || INSIDE_SYSTEM_WEB
  25. using System;
  26. using System.Threading;
  27. using System.Collections;
  28. using System.Collections.Generic;
  29. using System.Runtime.Serialization;
  30. namespace System.Collections.Concurrent
  31. {
  32. internal class SplitOrderedList<T>
  33. {
  34. class Node
  35. {
  36. public readonly bool Marked;
  37. public readonly ulong Key;
  38. public T Data;
  39. public Node Next;
  40. public Node (ulong key, T data)
  41. {
  42. this.Key = key;
  43. this.Data = data;
  44. }
  45. // Used to create marked node
  46. public Node (Node wrapped)
  47. {
  48. this.Marked = true;
  49. this.Next = wrapped;
  50. }
  51. }
  52. const int MaxLoad = 5;
  53. /*const uint SegmentSize = 1u << SegmentShift;
  54. const int SegmentShift = 5;*/
  55. const uint BucketSize = 512;
  56. /*[ThreadStatic]
  57. Node[] segmentCache;*/
  58. Node head;
  59. Node tail;
  60. //Node[][] buckets = new Node[BucketSize][];
  61. Node[] buckets = new Node [BucketSize];
  62. int count;
  63. int size = 2;
  64. SimpleRwLock slim = new SimpleRwLock ();
  65. public SplitOrderedList ()
  66. {
  67. head = new Node (0, default (T));
  68. tail = new Node (ulong.MaxValue, default (T));
  69. head.Next = tail;
  70. SetBucket (0, head);
  71. }
  72. public int Count {
  73. get {
  74. return count;
  75. }
  76. }
  77. public T InsertOrUpdate (uint key, Func<T> addGetter, Func<T, T> updateGetter)
  78. {
  79. Node current;
  80. bool result = InsertInternal (key, default (T), addGetter, out current);
  81. if (result)
  82. return current.Data;
  83. // FIXME: this should have a CAS-like behavior
  84. return current.Data = updateGetter (current.Data);
  85. }
  86. public T InsertOrUpdate (uint key, T addValue, T updateValue)
  87. {
  88. Node current;
  89. if (InsertInternal (key, addValue, null, out current))
  90. return current.Data;
  91. // FIXME: this should have a CAS-like behavior
  92. return current.Data = updateValue;
  93. }
  94. public bool Insert (uint key, T data)
  95. {
  96. Node current;
  97. return InsertInternal (key, data, null, out current);
  98. }
  99. public T InsertOrGet (uint key, T data, Func<T> dataCreator)
  100. {
  101. Node current;
  102. InsertInternal (key, data, dataCreator, out current);
  103. return current.Data;
  104. }
  105. bool InsertInternal (uint key, T data, Func<T> dataCreator, out Node current)
  106. {
  107. Node node = new Node (ComputeRegularKey (key), data);
  108. uint b = key % (uint)size;
  109. Node bucket;
  110. if ((bucket = GetBucket (b)) == null)
  111. bucket = InitializeBucket (b);
  112. if (!ListInsert (node, bucket, out current, dataCreator))
  113. return false;
  114. int csize = size;
  115. if (Interlocked.Increment (ref count) / csize > MaxLoad && (csize & 0x40000000) == 0)
  116. Interlocked.CompareExchange (ref size, 2 * csize, csize);
  117. current = node;
  118. return true;
  119. }
  120. public bool Find (uint key, out T data)
  121. {
  122. Node node;
  123. uint b = key % (uint)size;
  124. data = default (T);
  125. Node bucket;
  126. if ((bucket = GetBucket (b)) == null)
  127. bucket = InitializeBucket (b);
  128. if (!ListFind (ComputeRegularKey (key), bucket, out node))
  129. return false;
  130. data = node.Data;
  131. return !node.Marked;
  132. }
  133. public bool CompareExchange (uint key, T data, Func<T, bool> check)
  134. {
  135. Node node;
  136. uint b = key % (uint)size;
  137. Node bucket;
  138. if ((bucket = GetBucket (b)) == null)
  139. bucket = InitializeBucket (b);
  140. if (!ListFind (ComputeRegularKey (key), bucket, out node))
  141. return false;
  142. if (!check (node.Data))
  143. return false;
  144. node.Data = data;
  145. return true;
  146. }
  147. public bool Delete (uint key, out T data)
  148. {
  149. uint b = key % (uint)size;
  150. Node bucket;
  151. if ((bucket = GetBucket (b)) == null)
  152. bucket = InitializeBucket (b);
  153. if (!ListDelete (bucket, ComputeRegularKey (key), out data))
  154. return false;
  155. Interlocked.Decrement (ref count);
  156. return true;
  157. }
  158. public IEnumerator<T> GetEnumerator ()
  159. {
  160. Node node = head.Next;
  161. while (node != tail) {
  162. while (node.Marked || (node.Key & 1) == 0) {
  163. node = node.Next;
  164. if (node == tail)
  165. yield break;
  166. }
  167. yield return node.Data;
  168. node = node.Next;
  169. }
  170. }
  171. Node InitializeBucket (uint b)
  172. {
  173. Node current;
  174. uint parent = GetParent (b);
  175. Node bucket;
  176. if ((bucket = GetBucket (parent)) == null)
  177. bucket = InitializeBucket (parent);
  178. Node dummy = new Node (ComputeDummyKey (b), default (T));
  179. if (!ListInsert (dummy, bucket, out current, null))
  180. return current;
  181. return SetBucket (b, dummy);
  182. }
  183. // Turn v's MSB off
  184. static uint GetParent (uint v)
  185. {
  186. uint t, tt;
  187. // Find MSB position in v
  188. var pos = (tt = v >> 16) > 0 ?
  189. (t = tt >> 8) > 0 ? 24 + logTable[t] : 16 + logTable[tt] :
  190. (t = v >> 8) > 0 ? 8 + logTable[t] : logTable[v];
  191. return (uint)(v & ~(1 << pos));
  192. }
  193. // Reverse integer bits and make sure LSB is set
  194. static ulong ComputeRegularKey (uint key)
  195. {
  196. return ComputeDummyKey (key) | 1;
  197. }
  198. // Reverse integer bits
  199. static ulong ComputeDummyKey (uint key)
  200. {
  201. return ((ulong)(((uint)reverseTable[key & 0xff] << 24) |
  202. ((uint)reverseTable[(key >> 8) & 0xff] << 16) |
  203. ((uint)reverseTable[(key >> 16) & 0xff] << 8) |
  204. ((uint)reverseTable[(key >> 24) & 0xff]))) << 1;
  205. }
  206. // Bucket storage is abstracted in a simple two-layer tree to avoid too much memory resize
  207. Node GetBucket (uint index)
  208. {
  209. /*uint segment = index >> SegmentShift;
  210. if (buckets[segment] == null)
  211. return null;
  212. return buckets[segment][index & (SegmentSize - 1)];*/
  213. if (index >= buckets.Length)
  214. return null;
  215. return buckets[index];
  216. }
  217. Node SetBucket (uint index, Node node)
  218. {
  219. //uint segment = index >> SegmentShift;
  220. try {
  221. slim.EnterReadLock ();
  222. CheckSegment (index, true);
  223. /*if (buckets[segment] == null) {
  224. // Cache segment creation in case CAS fails
  225. Node[] newSegment = segmentCache == null ? new Node[SegmentSize] : segmentCache;
  226. segmentCache = Interlocked.CompareExchange (ref buckets[segment], newSegment, null) == null ? null : newSegment;
  227. }
  228. return buckets[segment][index & (SegmentSize - 1)] = node;*/
  229. Interlocked.CompareExchange (ref buckets[index], node, null);
  230. return buckets[index];
  231. } finally {
  232. slim.ExitReadLock ();
  233. }
  234. }
  235. // When we run out of space for bucket storage, we use a lock-based array resize
  236. void CheckSegment (uint segment, bool readLockTaken)
  237. {
  238. if (segment < buckets.Length)
  239. return;
  240. if (readLockTaken)
  241. slim.ExitReadLock ();
  242. try {
  243. slim.EnterWriteLock ();
  244. while (segment >= buckets.Length)
  245. Array.Resize (ref buckets, buckets.Length * 2);
  246. } finally {
  247. slim.ExitWriteLock ();
  248. }
  249. if (readLockTaken)
  250. slim.EnterReadLock ();
  251. }
  252. Node ListSearch (ulong key, ref Node left, Node h)
  253. {
  254. Node leftNodeNext = null, rightNode = null;
  255. do {
  256. Node t = h;
  257. Node tNext = t.Next;
  258. do {
  259. if (!tNext.Marked) {
  260. left = t;
  261. leftNodeNext = tNext;
  262. }
  263. t = tNext.Marked ? tNext.Next : tNext;
  264. if (t == tail)
  265. break;
  266. tNext = t.Next;
  267. } while (tNext.Marked || t.Key < key);
  268. rightNode = t;
  269. if (leftNodeNext == rightNode) {
  270. if (rightNode != tail && rightNode.Next.Marked)
  271. continue;
  272. else
  273. return rightNode;
  274. }
  275. if (Interlocked.CompareExchange (ref left.Next, rightNode, leftNodeNext) == leftNodeNext) {
  276. if (rightNode != tail && rightNode.Next.Marked)
  277. continue;
  278. else
  279. return rightNode;
  280. }
  281. } while (true);
  282. }
  283. bool ListDelete (Node startPoint, ulong key, out T data)
  284. {
  285. Node rightNode = null, rightNodeNext = null, leftNode = null;
  286. data = default (T);
  287. do {
  288. rightNode = ListSearch (key, ref leftNode, startPoint);
  289. if (rightNode == tail || rightNode.Key != key)
  290. return false;
  291. data = rightNode.Data;
  292. rightNodeNext = rightNode.Next;
  293. if (!rightNodeNext.Marked)
  294. if (Interlocked.CompareExchange (ref rightNode.Next, new Node (rightNodeNext), rightNodeNext) == rightNodeNext)
  295. break;
  296. } while (true);
  297. if (Interlocked.CompareExchange (ref leftNode.Next, rightNodeNext, rightNode) != rightNodeNext)
  298. ListSearch (rightNode.Key, ref leftNode, startPoint);
  299. return true;
  300. }
  301. bool ListInsert (Node newNode, Node startPoint, out Node current, Func<T> dataCreator)
  302. {
  303. ulong key = newNode.Key;
  304. Node rightNode = null, leftNode = null;
  305. do {
  306. rightNode = current = ListSearch (key, ref leftNode, startPoint);
  307. if (rightNode != tail && rightNode.Key == key)
  308. return false;
  309. newNode.Next = rightNode;
  310. if (dataCreator != null)
  311. newNode.Data = dataCreator ();
  312. if (Interlocked.CompareExchange (ref leftNode.Next, newNode, rightNode) == rightNode)
  313. return true;
  314. } while (true);
  315. }
  316. bool ListFind (ulong key, Node startPoint, out Node data)
  317. {
  318. Node rightNode = null, leftNode = null;
  319. data = null;
  320. rightNode = ListSearch (key, ref leftNode, startPoint);
  321. data = rightNode;
  322. return rightNode != tail && rightNode.Key == key;
  323. }
  324. static readonly byte[] reverseTable = {
  325. 0, 128, 64, 192, 32, 160, 96, 224, 16, 144, 80, 208, 48, 176, 112, 240, 8, 136, 72, 200, 40, 168, 104, 232, 24, 152, 88, 216, 56, 184, 120, 248, 4, 132, 68, 196, 36, 164, 100, 228, 20, 148, 84, 212, 52, 180, 116, 244, 12, 140, 76, 204, 44, 172, 108, 236, 28, 156, 92, 220, 60, 188, 124, 252, 2, 130, 66, 194, 34, 162, 98, 226, 18, 146, 82, 210, 50, 178, 114, 242, 10, 138, 74, 202, 42, 170, 106, 234, 26, 154, 90, 218, 58, 186, 122, 250, 6, 134, 70, 198, 38, 166, 102, 230, 22, 150, 86, 214, 54, 182, 118, 246, 14, 142, 78, 206, 46, 174, 110, 238, 30, 158, 94, 222, 62, 190, 126, 254, 1, 129, 65, 193, 33, 161, 97, 225, 17, 145, 81, 209, 49, 177, 113, 241, 9, 137, 73, 201, 41, 169, 105, 233, 25, 153, 89, 217, 57, 185, 121, 249, 5, 133, 69, 197, 37, 165, 101, 229, 21, 149, 85, 213, 53, 181, 117, 245, 13, 141, 77, 205, 45, 173, 109, 237, 29, 157, 93, 221, 61, 189, 125, 253, 3, 131, 67, 195, 35, 163, 99, 227, 19, 147, 83, 211, 51, 179, 115, 243, 11, 139, 75, 203, 43, 171, 107, 235, 27, 155, 91, 219, 59, 187, 123, 251, 7, 135, 71, 199, 39, 167, 103, 231, 23, 151, 87, 215, 55, 183, 119, 247, 15, 143, 79, 207, 47, 175, 111, 239, 31, 159, 95, 223, 63, 191, 127, 255
  326. };
  327. static readonly byte[] logTable = {
  328. 0xFF, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7
  329. };
  330. struct SimpleRwLock
  331. {
  332. const int RwWait = 1;
  333. const int RwWrite = 2;
  334. const int RwRead = 4;
  335. int rwlock;
  336. public void EnterReadLock ()
  337. {
  338. SpinWait sw = new SpinWait ();
  339. do {
  340. while ((rwlock & (RwWrite | RwWait)) > 0)
  341. sw.SpinOnce ();
  342. if ((Interlocked.Add (ref rwlock, RwRead) & (RwWait | RwWait)) == 0)
  343. return;
  344. Interlocked.Add (ref rwlock, -RwRead);
  345. } while (true);
  346. }
  347. public void ExitReadLock ()
  348. {
  349. Interlocked.Add (ref rwlock, -RwRead);
  350. }
  351. public void EnterWriteLock ()
  352. {
  353. SpinWait sw = new SpinWait ();
  354. do {
  355. int state = rwlock;
  356. if (state < RwWrite) {
  357. if (Interlocked.CompareExchange (ref rwlock, RwWrite, state) == state)
  358. return;
  359. state = rwlock;
  360. }
  361. // We register our interest in taking the Write lock (if upgradeable it's already done)
  362. while ((state & RwWait) == 0 && Interlocked.CompareExchange (ref rwlock, state | RwWait, state) != state)
  363. state = rwlock;
  364. // Before falling to sleep
  365. while (rwlock > RwWait)
  366. sw.SpinOnce ();
  367. } while (true);
  368. }
  369. public void ExitWriteLock ()
  370. {
  371. Interlocked.Add (ref rwlock, -RwWrite);
  372. }
  373. }
  374. }
  375. #if INSIDE_SYSTEM_WEB && !NET_4_0 && !BOOTSTRAP_NET_4_0
  376. internal struct SpinWait
  377. {
  378. const int step = 5;
  379. const int maxTime = 50;
  380. static readonly bool isSingleCpu = (Environment.ProcessorCount == 1);
  381. int ntime;
  382. public void SpinOnce ()
  383. {
  384. if (isSingleCpu) {
  385. // On a single-CPU system, spinning does no good
  386. Thread.Sleep (0);
  387. } else {
  388. if ((ntime = ntime == maxTime ? maxTime : ntime + 1) % step == 0)
  389. Thread.Sleep (0);
  390. else
  391. // Multi-CPU system might be hyper-threaded, let other thread run
  392. Thread.SpinWait (ntime << 1);
  393. }
  394. }
  395. }
  396. #endif
  397. }
  398. #endif