/// <summary> /// Returns the first actual (non-header) node on list. /// </summary> /// <returns>First node.</returns> Node <T> First() { for (; ;) { Node <T> h = _head; Node <T> t = _tail; Node <T> first = h.Next; if (h == _head) { if (h == t) { if (first == null) { return(null); } else { ThreadingUtils.CompareAndSwap(ref _tail, t, first); } } else { if (first.Item != null) { return(first); } else // remove deleted node and continue { ThreadingUtils.CompareAndSwap(ref _head, h, first); } } } } }
/// <summary> /// Inserts the specified element at the tail of this queue. /// </summary> /// <param name="item">The item to insert in the queue.</param> public void Enqueue(T item) { Node <T> oldTail = null; Node <T> oldTailNext; Node <T> newNode = new Node <T>(item); bool newNodeWasAdded = false; while (!newNodeWasAdded) { oldTail = _tail; oldTailNext = oldTail.Next; if (_tail == oldTail) { if (oldTailNext == null) { newNodeWasAdded = ThreadingUtils.CompareAndSwap(ref _tail.Next, null, newNode); } else { ThreadingUtils.CompareAndSwap(ref _tail, oldTail, oldTailNext); } } } ThreadingUtils.CompareAndSwap(ref _tail, oldTail, newNode); }
/// <summary> /// Removes an item from the queue. /// </summary> /// <param name="item">The dequeued item.</param> /// <returns> /// The dequeued item, or the default value for the element type if the queue was empty. /// </returns> public bool Dequeue(out T item) { item = default(T); Node <T> oldHead = null; bool haveAdvancedHead = false; while (!haveAdvancedHead) { oldHead = _head; Node <T> oldTail = _tail; Node <T> oldHeadNext = oldHead.Next; if (oldHead == _head) { if (oldHead == oldTail) { if (oldHeadNext == null) { return(false); } ThreadingUtils.CompareAndSwap(ref _tail, oldTail, oldHeadNext); } else { item = oldHeadNext.Item; haveAdvancedHead = ThreadingUtils.CompareAndSwap(ref _head, oldHead, oldHeadNext); } } } return(true); }