Esempio n. 1
0
        /// <summary>
        /// 讲对象添加到队列中
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public virtual bool Enqueue(T value)
        {
            var newTail = new MpscLinkedQueueNode <T>()
            {
                Value = value, Next = null
            };

            //F0:1将tail修改为newTail
            var oldTail = GetAndSetTailByCAS(newTail);

            //F1:2将oldTail的Next修改为newTail
            oldTail.Next = newTail;

            return(true);
        }
Esempio n. 2
0
        /// <summary>
        /// 从队列中取出一个项
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// 该方法只适合单个消费者
        /// </remarks>
        public virtual T Dequeue()
        {
            var next = PeekNode();

            if (next == null)
            {
                return(null);
            }

            this.head.Next = next.Next;

            if (this.tail == next)
            {
                this.tail = this.head;
            }

            return(next.Value);
        }
Esempio n. 3
0
 /// <summary>
 /// 适合多个生产者一个消费者的单向队列
 /// </summary>
 public MpscLinkedQueue()
 {
     head = tail = defaultNode;
 }
Esempio n. 4
0
 /// <summary>
 /// 获取并设置Tail,该操作是原子操作
 /// </summary>
 /// <param name="value"></param>
 /// <returns></returns>
 private MpscLinkedQueueNode <T> GetAndSetTailByCAS(MpscLinkedQueueNode <T> value)
 {
     return(Interlocked.Exchange(ref this.tail, value));
 }