Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.88 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3.  
  4. namespace System.Collections.Generic
  5. {
  6. public sealed class LockFreeQueue<T> where T : class
  7. {
  8. private class SingleLinkNode
  9. {
  10. public SingleLinkNode Next;
  11. public T Item;
  12. }
  13.  
  14. private SingleLinkNode mHead = null;
  15. private SingleLinkNode mTail = null;
  16.  
  17. public LockFreeQueue()
  18. {
  19. mHead = new SingleLinkNode();
  20. mTail = mHead;
  21. }
  22.  
  23. private static bool CompareAndExchange(ref SingleLinkNode pLocation, SingleLinkNode pComparand, SingleLinkNode pNewValue)
  24. {
  25. return
  26. (object)pComparand ==
  27. (object)Interlocked.CompareExchange<SingleLinkNode>(ref pLocation, pNewValue, pComparand);
  28. }
  29.  
  30. public T Next { get { return mHead.Next == null ? null : mHead.Next.Item; } }
  31. public void Enqueue(T pItem)
  32. {
  33. SingleLinkNode oldTail = null;
  34. SingleLinkNode oldTailNext;
  35.  
  36. SingleLinkNode newNode = new SingleLinkNode();
  37. newNode.Item = pItem;
  38.  
  39. bool newNodeWasAdded = false;
  40. while (!newNodeWasAdded)
  41. {
  42. oldTail = mTail;
  43. oldTailNext = oldTail.Next;
  44.  
  45. if (mTail == oldTail)
  46. {
  47. if (oldTailNext == null)
  48. newNodeWasAdded = CompareAndExchange(ref mTail.Next, null, newNode);
  49. else
  50. CompareAndExchange(ref mTail, oldTail, oldTailNext);
  51. }
  52. }
  53.  
  54. CompareAndExchange(ref mTail, oldTail, newNode);
  55. }
  56.  
  57. public bool Dequeue(out T pItem)
  58. {
  59. pItem = default(T);
  60. SingleLinkNode oldHead = null;
  61.  
  62. bool haveAdvancedHead = false;
  63. while (!haveAdvancedHead)
  64. {
  65.  
  66. oldHead = mHead;
  67. SingleLinkNode oldTail = mTail;
  68. SingleLinkNode oldHeadNext = oldHead.Next;
  69.  
  70. if (oldHead == mHead)
  71. {
  72. if (oldHead == oldTail)
  73. {
  74. if (oldHeadNext == null)
  75. {
  76. return false;
  77. }
  78. CompareAndExchange(ref mTail, oldTail, oldHeadNext);
  79. }
  80.  
  81. else
  82. {
  83. pItem = oldHeadNext.Item;
  84. haveAdvancedHead =
  85. CompareAndExchange(ref mHead, oldHead, oldHeadNext);
  86. }
  87. }
  88. }
  89. return true;
  90. }
  91.  
  92. public T Dequeue()
  93. {
  94. T result;
  95. Dequeue(out result);
  96. return result;
  97. }
  98. }
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement