예제 #1
0
        /// <summary>
        /// Adds an object to the end of the queue.
        /// </summary>
        /// <param name="item">the object to add to the queue</param>
        public void Enqueue(T item)
        {
            SingleLinkNode <T> oldTail = null;

            var newNode = new SingleLinkNode <T> {
                Item = item
            };

            var newNodeWasAdded = false;

            while (!newNodeWasAdded)
            {
                oldTail = _tail;
                var oldTailNext = oldTail.Next;

                if (_tail != oldTail)
                {
                    continue;
                }

                if (oldTailNext == null)
                {
                    newNodeWasAdded =
                        Interlocked.CompareExchange(ref _tail.Next, newNode, null) == null;
                }
                else
                {
                    Interlocked.CompareExchange(ref _tail, oldTailNext, oldTail);
                }
            }

            Interlocked.CompareExchange(ref _tail, newNode, oldTail);
            Interlocked.Increment(ref _count);
        }
예제 #2
0
        /// <summary>
        /// Clears the queue.
        /// </summary>
        /// <remarks>This method is not thread-safe.</remarks>
        public void Clear()
        {
            var currentNode = _head;

            while (currentNode != null)
            {
                var tempNode = currentNode;
                currentNode = currentNode.Next;

                tempNode.Item = default(T);
                tempNode.Next = null;
            }

            _head  = new SingleLinkNode <T>();
            _tail  = _head;
            _count = 0;
        }
예제 #3
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 public LockFreeQueue()
 {
     _head = new SingleLinkNode <T>();
     _tail = _head;
 }