Esempio n. 1
0
        /// <summary>
        /// Lock free peek using ordered loads. As class name suggests access is limited to a single thread.
        /// </summary>
        /// <param name="item">The peeked item.</param>
        /// <returns><c>true</c> if an item was retrieved, otherwise <c>false</c>.</returns>
        /// <seealso cref="IQueue{T}.TryPeek"/>
        public override bool TryPeek(out T item)
        {
            // Copy field to avoid re-reading after volatile load
            T[] buffer = this.Buffer;

            long consumerIndex = this.ConsumerIndex; // LoadLoad
            long offset        = this.CalcElementOffset(consumerIndex);
            T    e             = RefArrayAccessUtil.LvElement(buffer, offset);

            if (null == e)
            {
                // NOTE: Queue may not actually be empty in the case of a producer (P1) being interrupted after
                // winning the CAS on offer but before storing the element in the queue. Other producers may go on
                // to fill up the queue after this element.

                if (consumerIndex != this.ProducerIndex)
                {
                    do
                    {
                        e = RefArrayAccessUtil.LvElement(buffer, offset);
                    } while (e == null);
                }
                else
                {
                    item = default(T);
                    return(false);
                }
            }

            item = e;

            return(true);
        }
Esempio n. 2
0
 /// <summary>
 /// A volatile load (load + LoadLoad barrier) of an element from a given offset.
 /// </summary>
 /// <param name="offset">Computed via <see cref="CalcElementOffset"/>.</param>
 /// <returns>The element at the offset.</returns>
 protected T LvElement(long offset) => RefArrayAccessUtil.LvElement(this.Buffer, offset);