System.Threading.Interlocked.Add(ref long, long)

Here are the examples of the csharp api System.Threading.Interlocked.Add(ref long, long) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

600 Examples 7

19 View Source File : RtmpSession.cs
License : MIT License
Project Creator : a1q123456

private void HandleAcknowledgement(AcknowledgementMessage ack)
        {
            Interlocked.Add(ref IOPipeline.ChunkStreamContext.WriteUnAcknowledgedSize, ack.BytesReceived * -1);
        }

19 View Source File : ChunkStreamContext.cs
License : MIT License
Project Creator : a1q123456

internal async Task MultiplexMessageAsync(uint chunkStreamId, Message message)
        {
            if (!message.MessageHeader.MessageStreamId.HasValue)
            {
                throw new InvalidOperationException("cannot send message that has not attached to a message stream");
            }
            byte[] buffer = null;
            uint length = 0;
            using (var writeBuffer = new ByteBuffer())
            {
                var context = new Serialization.SerializationContext()
                {
                    Amf0Reader = _amf0Reader,
                    Amf0Writer = _amf0Writer,
                    Amf3Reader = _amf3Reader,
                    Amf3Writer = _amf3Writer,
                    WriteBuffer = writeBuffer
                };
                message.Serialize(context);
                length = (uint)writeBuffer.Length;
                Debug.replacedert(length != 0);
                buffer = _arrayPool.Rent((int)length);
                writeBuffer.TakeOutMemory(buffer);
            }

            try
            {
                message.MessageHeader.MessageLength = length;
                Debug.replacedert(message.MessageHeader.MessageLength != 0);
                if (message.MessageHeader.MessageType == 0)
                {
                    message.MessageHeader.MessageType = message.GetType().GetCustomAttribute<RtmpMessageAttribute>().MessageTypes.First();
                }
                Debug.replacedert(message.MessageHeader.MessageType != 0);
                Task ret = null;
                // chunking
                bool isFirstChunk = true;
                _rtmpSession.replacedertStreamId(message.MessageHeader.MessageStreamId.Value);
                for (int i = 0; i < message.MessageHeader.MessageLength;)
                {
                    _previousWriteMessageHeader.TryGetValue(chunkStreamId, out var prevHeader);
                    var chunkHeaderType = SelectChunkType(message.MessageHeader, prevHeader, isFirstChunk);
                    isFirstChunk = false;
                    GenerateBasicHeader(chunkHeaderType, chunkStreamId, out var basicHeader, out var basicHeaderLength);
                    GenerateMesesageHeader(chunkHeaderType, message.MessageHeader, prevHeader, out var messageHeader, out var messageHeaderLength);
                    _previousWriteMessageHeader[chunkStreamId] = (MessageHeader)message.MessageHeader.Clone();
                    var headerLength = basicHeaderLength + messageHeaderLength;
                    var bodySize = (int)(length - i >= _writeChunkSize ? _writeChunkSize : length - i);

                    var chunkBuffer = _arrayPool.Rent(headerLength + bodySize);
                    await _sync.WaitAsync();
                    try
                    {
                        basicHeader.replacedpan(0, basicHeaderLength).CopyTo(chunkBuffer);
                        messageHeader.replacedpan(0, messageHeaderLength).CopyTo(chunkBuffer.replacedpan(basicHeaderLength));
                        _arrayPool.Return(basicHeader);
                        _arrayPool.Return(messageHeader);
                        buffer.replacedpan(i, bodySize).CopyTo(chunkBuffer.replacedpan(headerLength));
                        i += bodySize;
                        var isLastChunk = message.MessageHeader.MessageLength - i == 0;

                        long offset = 0;
                        long totalLength = headerLength + bodySize;
                        long currentSendSize = totalLength;

                        while (offset != (headerLength + bodySize))
                        {
                            if (WriteWindowAcknowledgementSize.HasValue && Interlocked.Read(ref WriteUnAcknowledgedSize) + headerLength + bodySize > WriteWindowAcknowledgementSize.Value)
                            {
                                currentSendSize = Math.Min(WriteWindowAcknowledgementSize.Value, currentSendSize);
                                //var delayCount = 0;
                                while (currentSendSize + Interlocked.Read(ref WriteUnAcknowledgedSize) >= WriteWindowAcknowledgementSize.Value)
                                {
                                    await Task.Delay(1);
                                }
                            }
                            var tsk = _ioPipeline.SendRawData(chunkBuffer.AsMemory((int)offset, (int)currentSendSize));
                            offset += currentSendSize;
                            totalLength -= currentSendSize;

                            if (WriteWindowAcknowledgementSize.HasValue)
                            {
                                Interlocked.Add(ref WriteUnAcknowledgedSize, currentSendSize);
                            }
                            
                            if (isLastChunk)
                            {
                                ret = tsk;
                            }
                        }
                        if (isLastChunk)
                        {
                            if (message.MessageHeader.MessageType == MessageType.SetChunkSize)
                            {
                                var setChunkSize = message as SetChunkSizeMessage;
                                _writeChunkSize = setChunkSize.ChunkSize;
                            }
                            else if (message.MessageHeader.MessageType == MessageType.SetPeerBandwidth)
                            {
                                var m = message as SetPeerBandwidthMessage;
                                ReadWindowAcknowledgementSize = m.WindowSize;
                            }
                            else if (message.MessageHeader.MessageType == MessageType.WindowAcknowledgementSize)
                            {
                                var m = message as WindowAcknowledgementSizeMessage;
                                WriteWindowAcknowledgementSize = m.WindowSize;
                            }
                        }
                    }
                    finally
                    {
                        _sync.Release();
                        _arrayPool.Return(chunkBuffer);
                    }
                }
                Debug.replacedert(ret != null);
                await ret;

            }
            finally
            {
                _arrayPool.Return(buffer);
            }

        }

19 View Source File : ExecutionContext.cs
License : MIT License
Project Creator : actions

private void JobServerQueueThrottling_EventReceived(object sender, ThrottlingEventArgs data)
        {
            Interlocked.Add(ref _totalThrottlingDelayInMilliseconds, Convert.ToInt64(data.Delay.TotalMilliseconds));

            if (!_throttlingReported &&
                _totalThrottlingDelayInMilliseconds > _throttlingDelayReportThreshold)
            {
                this.Warning(string.Format("The job is currently being throttled by the server. You may experience delays in console line output, job status reporting, and action log uploads."));

                _throttlingReported = true;
            }
        }

19 View Source File : Tester.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

void Async()
        {
            Interlocked.Increment(ref WaitCount);
            GlobalContext.SetRequestContext(ZeroApplication.Config.ServiceName, Guid.NewGuid().ToString("N"));
            DateTime s = DateTime.Now;

            DoAsync();

            Interlocked.Decrement(ref WaitCount);
            var sp = (DateTime.Now - s);
            Interlocked.Add(ref RunTime, sp.Ticks);
            if (sp.TotalMilliseconds > 500)
                Interlocked.Increment(ref TmError);
            if ((Interlocked.Increment(ref ExCount) % 100) == 0)
                Count();
        }

19 View Source File : MaybeConcatEager.cs
License : Apache License 2.0
Project Creator : akarnokd

internal override void Drain()
            {
                if (Interlocked.Increment(ref wip) != 1)
                {
                    return;
                }

                var missed = 1;
                var observers = this.observers;
                var downstream = this.downstream;
                var delayErrors = this.delayErrors;
                var sources = this.sources;
                var n = sources.Length;

                for (; ; )
                {
                    if (Volatile.Read(ref disposed))
                    {
                        while (observers.TryDequeue(out var inner))
                        {
                            inner.Dispose();
                        }
                    }
                    else
                    {
                        if (!delayErrors)
                        {
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                Volatile.Write(ref disposed, true);
                                downstream.OnError(ex);
                                continue;
                            }
                        }

                        var idx = index;
                        if (active < maxConcurrency && idx < n)
                        {
                            var src = sources[idx];

                            index = idx + 1;
                            active++;

                            SubscribeTo(src);
                            continue;
                        }

                        var d = index == n;
                        var empty = !observers.TryPeek(out var inner);

                        if (d && empty)
                        {
                            Volatile.Write(ref disposed, true);
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                downstream.OnError(ex);
                            }
                            else
                            {
                                downstream.OnCompleted();
                            }
                        }
                        else
                        if (!empty)
                        {
                            var state = inner.GetState();

                            if (state == 1)
                            {
                                downstream.OnNext(inner.value);
                                observers.TryDequeue(out var _);
                                active--;
                                continue;
                            }
                            else
                            if (state == 2)
                            {
                                observers.TryDequeue(out var _);
                                active--;
                                continue;
                            }
                        }
                    }

                    missed = Interlocked.Add(ref wip, -missed);
                    if (missed == 0)
                    {
                        break;
                    }
                }
            }

19 View Source File : MaybeConcatEagerEnumerable.cs
License : Apache License 2.0
Project Creator : akarnokd

internal override void Drain()
            {
                if (Interlocked.Increment(ref wip) != 1)
                {
                    return;
                }

                var missed = 1;
                var observers = this.observers;
                var downstream = this.downstream;
                var delayErrors = this.delayErrors;
                var sources = this.sources;

                for (; ; )
                {
                    if (Volatile.Read(ref disposed))
                    {
                        while (observers.TryDequeue(out var inner))
                        {
                            inner.Dispose();
                        }
                        if (sources != null)
                        {
                            this.sources = null;
                            sources.Dispose();
                        }
                    }
                    else
                    {
                        if (!delayErrors)
                        {
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                Volatile.Write(ref disposed, true);
                                downstream.OnError(ex);
                                continue;
                            }
                        }

                        if (active < maxConcurrency && !done)
                        {

                            var src = default(IMaybeSource<T>);

                            try
                            {
                                if (sources.MoveNext())
                                {
                                    src = sources.Current;
                                }
                                else
                                {
                                    done = true;
                                }
                            }
                            catch (Exception ex)
                            {
                                done = true;
                                sources.Dispose();
                                this.sources = null;

                                if (delayErrors)
                                {
                                    ExceptionHelper.AddException(ref errors, ex);
                                }
                                else
                                {
                                    Interlocked.CompareExchange(ref errors, ex, null);
                                }
                                continue;
                            }

                            if (!done)
                            {
                                active++;

                                SubscribeTo(src);
                                continue;
                            }
                            else
                            {
                                sources.Dispose();
                                this.sources = null;
                            }
                        }

                        var d = done;
                        var empty = !observers.TryPeek(out var inner);

                        if (d && empty)
                        {
                            Volatile.Write(ref disposed, true);
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                downstream.OnError(ex);
                            }
                            else
                            {
                                downstream.OnCompleted();
                            }
                        }
                        else
                        if (!empty)
                        {
                            var state = inner.GetState();

                            if (state == 1)
                            {
                                downstream.OnNext(inner.value);
                                observers.TryDequeue(out var _);
                                active--;
                                continue;
                            }
                            else
                            if (state == 2)
                            {
                                observers.TryDequeue(out var _);
                                active--;
                                continue;
                            }
                        }
                    }

                    missed = Interlocked.Add(ref wip, -missed);
                    if (missed == 0)
                    {
                        break;
                    }
                }
            }

19 View Source File : MaybeConcatMapEager.cs
License : Apache License 2.0
Project Creator : akarnokd

internal override void Drain()
            {
                if (Interlocked.Increment(ref wip) != 1)
                {
                    return;
                }

                var missed = 1;
                var observers = this.observers;
                var downstream = this.downstream;
                var delayErrors = this.delayErrors;
                var sources = this.queue;

                for (; ; )
                {
                    if (Volatile.Read(ref disposed))
                    {
                        while (observers.TryDequeue(out var inner))
                        {
                            inner.Dispose();
                        }

                        while (sources.TryDequeue(out var _)) ;
                    }
                    else
                    {
                        if (!delayErrors)
                        {
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                Volatile.Write(ref disposed, true);
                                downstream.OnError(ex);
                                DisposableHelper.Dispose(ref upstream);
                                continue;
                            }
                        }

                        if (!noMoreSources && active < maxConcurrency && !sources.IsEmpty)
                        {

                            if (sources.TryDequeue(out var v))
                            {
                                var src = default(IMaybeSource<R>);
                                try
                                {
                                    src = RequireNonNullRef(mapper(v), "The mapper returned a null IMaybeSource");
                                }
                                catch (Exception ex)
                                {
                                    if (delayErrors)
                                    {
                                        ExceptionHelper.AddException(ref errors, ex);
                                        Volatile.Write(ref done, true);

                                    }
                                    else
                                    {
                                        Interlocked.CompareExchange(ref errors, ex, null);
                                    }
                                    noMoreSources = true;
                                    DisposableHelper.Dispose(ref upstream);
                                    continue;
                                }

                                active++;

                                SubscribeTo(src);
                                continue;
                            }
                        }

                        var d = Volatile.Read(ref done) && sources.IsEmpty;
                        var empty = !observers.TryPeek(out var inner);

                        if (d && empty)
                        {
                            Volatile.Write(ref disposed, true);
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                downstream.OnError(ex);
                            }
                            else
                            {
                                downstream.OnCompleted();
                            }
                            DisposableHelper.Dispose(ref upstream);
                        }
                        else
                        if (!empty)
                        {
                            var state = inner.GetState();

                            if (state == 1)
                            {
                                downstream.OnNext(inner.value);
                                observers.TryDequeue(out var _);
                                active--;
                                continue;
                            }
                            else
                            if (state == 2)
                            {
                                observers.TryDequeue(out var _);
                                active--;
                                continue;
                            }
                        }
                    }

                    missed = Interlocked.Add(ref wip, -missed);
                    if (missed == 0)
                    {
                        break;
                    }
                }
            }

19 View Source File : MaybeFlatMapMany.cs
License : Apache License 2.0
Project Creator : akarnokd

internal override void DrainLoop()
            {
                var missed = 1;

                var sources = this.sources;
                var downstream = this.downstream;
                var maxConcurrency = this.maxConcurrency;

                for (; ; )
                {
                    if (IsDisposed())
                    {
                        while (sources.TryDequeue(out var _)) ;
                    }
                    else
                    {
                        if (!delayErrors)
                        {
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                Dispose();
                                downstream.OnError(ex);
                                continue;
                            }
                        }

                        var d = Volatile.Read(ref done);
                        var running = Volatile.Read(ref active);

                        if (!noMoreSources && running < maxConcurrency)
                        {

                            var src = default(IMaybeSource<R>);
                            var has = sources.TryDequeue(out var t);

                            if (has)
                            {
                                try
                                {
                                    src = RequireNonNullRef(mapper(t), "The mapper returned a null IMaybeSource");
                                }
                                catch (Exception ex)
                                {
                                    if (delayErrors)
                                    {
                                        ExceptionHelper.AddException(ref errors, ex);
                                    }
                                    else
                                    {
                                        Interlocked.CompareExchange(ref errors, ex, null);
                                    }
                                    noMoreSources = true;
                                    Volatile.Write(ref done, true);
                                }

                                if (!noMoreSources)
                                {
                                    Interlocked.Increment(ref active);

                                    SubscribeTo(src);
                                }
                                continue;
                            }
                            else
                            {
                                if (d)
                                {
                                    noMoreSources = true;
                                }
                            }
                        }

                        var q = GetQueue();

                        var v = default(R);

                        var empty = q == null || !q.TryDequeue(out v);

                        if (d && running == 0 && noMoreSources && empty)
                        {
                            Volatile.Write(ref disposed, true);
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                downstream.OnError(ex);
                            }
                            else
                            {
                                downstream.OnCompleted();
                            }
                        }
                        else
                        if (!empty)
                        {
                            downstream.OnNext(v);
                            continue;
                        }
                    }

                    missed = Interlocked.Add(ref wip, -missed);
                    if (missed == 0)
                    {
                        break;
                    }
                }
            }

19 View Source File : MaybeFlatMapMany.cs
License : Apache License 2.0
Project Creator : akarnokd

internal override void DrainLoop()
            {
                var missed = 1;
                var downstream = this.downstream;

                for (; ; )
                {
                    if (!IsDisposed())
                    {
                        if (!delayErrors)
                        {
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                Dispose();
                                downstream.OnError(ex);
                                continue;
                            }
                        }

                        var d = Volatile.Read(ref active) == 0;

                        var q = GetQueue();

                        var v = default(R);
                        var empty = q == null || !q.TryDequeue(out v);

                        if (d && empty)
                        {
                            Volatile.Write(ref disposed, true);
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                downstream.OnError(ex);
                            }
                            else
                            {
                                downstream.OnCompleted();
                            }
                        }
                        else
                        if (!empty)
                        {
                            downstream.OnNext(v);
                            continue;
                        }
                    }

                    missed = Interlocked.Add(ref wip, -missed);
                    if (missed == 0)
                    {
                        break;
                    }
                }
            }

19 View Source File : MaybeMerge.cs
License : Apache License 2.0
Project Creator : akarnokd

internal override void DrainLoop()
            {
                var missed = 1;

                var sources = this.sources;
                var n = sources.Length;
                var downstream = this.downstream;

                for (; ; )
                {
                    if (!IsDisposed())
                    {
                        if (!delayErrors)
                        {
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                Dispose();
                                downstream.OnError(ex);
                                continue;
                            }
                        }

                        var d = Volatile.Read(ref active);

                        var idx = index;
                        if (d < maxConcurrency && idx < n)
                        {
                            var src = sources[idx];

                            if (src == null)
                            {
                                var ex = new NullReferenceException("The IMaybeSource at index " + idx + " is null");
                                if (delayErrors)
                                {
                                    ExceptionHelper.AddException(ref errors, ex);
                                } else
                                {
                                    Interlocked.CompareExchange(ref errors, ex, null);
                                }
                                index = n;
                            }
                            else
                            {
                                index = idx + 1;
                                Interlocked.Increment(ref active);

                                SubscribeTo(src);
                            }
                            continue;
                        }

                        var q = GetQueue();

                        var v = default(T);

                        var empty = q == null || !q.TryDequeue(out v);

                        if (d == 0 && empty)
                        {
                            Volatile.Write(ref disposed, true);
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                downstream.OnError(ex);
                            }
                            else
                            {
                                downstream.OnCompleted();
                            }
                        }
                        else
                        if (!empty)
                        {
                            downstream.OnNext(v);
                            continue;
                        }
                    }

                    missed = Interlocked.Add(ref wip, -missed);
                    if (missed == 0)
                    {
                        break;
                    }
                }
            }

19 View Source File : MaybeMerge.cs
License : Apache License 2.0
Project Creator : akarnokd

internal override void DrainLoop()
            {
                var missed = 1;
                var downstream = this.downstream;

                for (; ; )
                {
                    if (!IsDisposed())
                    {
                        if (!delayErrors)
                        {
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                Dispose();
                                downstream.OnError(ex);
                                continue;
                            }
                        }

                        var d = Volatile.Read(ref active) == 0;

                        var q = GetQueue();

                        var v = default(T);
                        var empty = q == null || !q.TryDequeue(out v);

                        if (d && empty)
                        {
                            Volatile.Write(ref disposed, true);
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                downstream.OnError(ex);
                            }
                            else
                            {
                                downstream.OnCompleted();
                            }
                        }
                        else
                        if (!empty)
                        {
                            downstream.OnNext(v);
                            continue;
                        }
                    }

                    missed = Interlocked.Add(ref wip, -missed);
                    if (missed == 0)
                    {
                        break;
                    }
                }
            }

19 View Source File : MaybeMergeEnumerable.cs
License : Apache License 2.0
Project Creator : akarnokd

internal override void DrainLoop()
            {
                var missed = 1;

                var sources = this.sources;
                var downstream = this.downstream;

                for (; ; )
                {
                    if (IsDisposed())
                    {
                        if (sources != null)
                        {
                            this.sources = null;
                            sources.Dispose();
                        }
                    }
                    else
                    {
                        if (!delayErrors)
                        {
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                Dispose();
                                downstream.OnError(ex);
                                continue;
                            }
                        }

                        var d = Volatile.Read(ref active);

                        if (!noMoreSources && d < maxConcurrency)
                        {
                            var src = default(IMaybeSource<T>);

                            try
                            {
                                if (sources.MoveNext())
                                {
                                    src = RequireNonNullRef(sources.Current, "The IEnumerator returned a null IMaybeSource");
                                }
                                else
                                {
                                    noMoreSources = true;
                                }
                            }
                            catch (Exception ex)
                            {
                                if (delayErrors)
                                {
                                    ExceptionHelper.AddException(ref errors, ex);
                                }
                                else
                                {
                                    Interlocked.CompareExchange(ref errors, ex, null);
                                }
                                noMoreSources = true;
                            }

                            if (noMoreSources)
                            {
                                this.sources = null;
                                sources.Dispose();
                            }
                            else
                            {
                                Interlocked.Increment(ref active);

                                SubscribeTo(src);
                                continue;
                            }
                        }

                        var q = GetQueue();

                        var v = default(T);

                        var empty = q == null || !q.TryDequeue(out v);

                        if (d == 0 && noMoreSources && empty)
                        {
                            Volatile.Write(ref disposed, true);
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                downstream.OnError(ex);
                            }
                            else
                            {
                                downstream.OnCompleted();
                            }
                        }
                        else
                        if (!empty)
                        {
                            downstream.OnNext(v);
                            continue;
                        }
                    }

                    missed = Interlocked.Add(ref wip, -missed);
                    if (missed == 0)
                    {
                        break;
                    }
                }
            }

19 View Source File : SingleMerge.cs
License : Apache License 2.0
Project Creator : akarnokd

internal override void DrainLoop()
            {
                var missed = 1;

                var sources = this.sources;
                var n = sources.Length;
                var downstream = this.downstream;

                for (; ; )
                {
                    if (!IsDisposed())
                    {
                        if (!delayErrors)
                        {
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                Dispose();
                                downstream.OnError(ex);
                                continue;
                            }
                        }

                        var d = Volatile.Read(ref active);

                        var idx = index;
                        if (d < maxConcurrency && idx < n)
                        {
                            var src = sources[idx];

                            if (src == null)
                            {
                                var ex = new NullReferenceException("The ISingleSource at index " + idx + " is null");
                                if (delayErrors)
                                {
                                    ExceptionHelper.AddException(ref errors, ex);
                                } else
                                {
                                    Interlocked.CompareExchange(ref errors, ex, null);
                                }
                                index = n;
                            }
                            else
                            {
                                index = idx + 1;
                                Interlocked.Increment(ref active);

                                SubscribeTo(src);
                            }
                            continue;
                        }

                        var q = GetQueue();

                        var v = default(T);

                        var empty = q == null || !q.TryDequeue(out v);

                        if (d == 0 && empty)
                        {
                            Volatile.Write(ref disposed, true);
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                downstream.OnError(ex);
                            }
                            else
                            {
                                downstream.OnCompleted();
                            }
                        }
                        else
                        if (!empty)
                        {
                            downstream.OnNext(v);
                            continue;
                        }
                    }

                    missed = Interlocked.Add(ref wip, -missed);
                    if (missed == 0)
                    {
                        break;
                    }
                }
            }

19 View Source File : SingleMergeEnumerable.cs
License : Apache License 2.0
Project Creator : akarnokd

internal override void DrainLoop()
            {
                var missed = 1;

                var sources = this.sources;
                var downstream = this.downstream;

                for (; ; )
                {
                    if (IsDisposed())
                    {
                        if (sources != null)
                        {
                            this.sources = null;
                            sources.Dispose();
                        }
                    }
                    else
                    {
                        if (!delayErrors)
                        {
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                Dispose();
                                downstream.OnError(ex);
                                continue;
                            }
                        }

                        var d = Volatile.Read(ref active);

                        if (!noMoreSources && d < maxConcurrency)
                        {
                            var src = default(ISingleSource<T>);

                            try
                            {
                                if (sources.MoveNext())
                                {
                                    src = RequireNonNullRef(sources.Current, "The IEnumerator returned a null ISingleSource");
                                }
                                else
                                {
                                    noMoreSources = true;
                                }
                            }
                            catch (Exception ex)
                            {
                                if (delayErrors)
                                {
                                    ExceptionHelper.AddException(ref errors, ex);
                                }
                                else
                                {
                                    Interlocked.CompareExchange(ref errors, ex, null);
                                }
                                noMoreSources = true;
                            }

                            if (noMoreSources)
                            {
                                this.sources = null;
                                sources.Dispose();
                            }
                            else
                            {
                                Interlocked.Increment(ref active);

                                SubscribeTo(src);
                                continue;
                            }
                        }

                        var q = GetQueue();

                        var v = default(T);

                        var empty = q == null || !q.TryDequeue(out v);

                        if (d == 0 && noMoreSources && empty)
                        {
                            Volatile.Write(ref disposed, true);
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                downstream.OnError(ex);
                            }
                            else
                            {
                                downstream.OnCompleted();
                            }
                        }
                        else
                        if (!empty)
                        {
                            downstream.OnNext(v);
                            continue;
                        }
                    }

                    missed = Interlocked.Add(ref wip, -missed);
                    if (missed == 0)
                    {
                        break;
                    }
                }
            }

19 View Source File : SingleConcatEagerEnumerable.cs
License : Apache License 2.0
Project Creator : akarnokd

internal override void Drain()
            {
                if (Interlocked.Increment(ref wip) != 1)
                {
                    return;
                }

                var missed = 1;
                var observers = this.observers;
                var downstream = this.downstream;
                var delayErrors = this.delayErrors;
                var sources = this.sources;

                for (; ; )
                {
                    if (Volatile.Read(ref disposed))
                    {
                        while (observers.TryDequeue(out var inner))
                        {
                            inner.Dispose();
                        }
                        if (sources != null)
                        {
                            this.sources = null;
                            sources.Dispose();
                        }
                    }
                    else
                    {
                        if (!delayErrors)
                        {
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                Volatile.Write(ref disposed, true);
                                downstream.OnError(ex);
                                continue;
                            }
                        }

                        if (active < maxConcurrency && !done)
                        {

                            var src = default(ISingleSource<T>);

                            try
                            {
                                if (sources.MoveNext())
                                {
                                    src = sources.Current;
                                }
                                else
                                {
                                    done = true;
                                }
                            }
                            catch (Exception ex)
                            {
                                done = true;
                                sources.Dispose();
                                this.sources = null;

                                if (delayErrors)
                                {
                                    ExceptionHelper.AddException(ref errors, ex);
                                }
                                else
                                {
                                    Interlocked.CompareExchange(ref errors, ex, null);
                                }
                                continue;
                            }

                            if (!done)
                            {
                                active++;

                                SubscribeTo(src);
                                continue;
                            }
                            else
                            {
                                sources.Dispose();
                                this.sources = null;
                            }
                        }

                        var d = done;
                        var empty = !observers.TryPeek(out var inner);

                        if (d && empty)
                        {
                            Volatile.Write(ref disposed, true);
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                downstream.OnError(ex);
                            }
                            else
                            {
                                downstream.OnCompleted();
                            }
                        }
                        else
                        if (!empty)
                        {
                            var state = inner.GetState();

                            if (state == 1)
                            {
                                downstream.OnNext(inner.value);
                                observers.TryDequeue(out var _);
                                active--;
                                continue;
                            }
                            else
                            if (state == 2)
                            {
                                observers.TryDequeue(out var _);
                                active--;
                                continue;
                            }
                        }
                    }

                    missed = Interlocked.Add(ref wip, -missed);
                    if (missed == 0)
                    {
                        break;
                    }
                }
            }

19 View Source File : SingleConcatMapEager.cs
License : Apache License 2.0
Project Creator : akarnokd

internal override void Drain()
            {
                if (Interlocked.Increment(ref wip) != 1)
                {
                    return;
                }

                var missed = 1;
                var observers = this.observers;
                var downstream = this.downstream;
                var delayErrors = this.delayErrors;
                var sources = this.queue;

                for (; ; )
                {
                    if (Volatile.Read(ref disposed))
                    {
                        while (observers.TryDequeue(out var inner))
                        {
                            inner.Dispose();
                        }

                        while (sources.TryDequeue(out var _)) ;
                    }
                    else
                    {
                        if (!delayErrors)
                        {
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                Volatile.Write(ref disposed, true);
                                downstream.OnError(ex);
                                DisposableHelper.Dispose(ref upstream);
                                continue;
                            }
                        }

                        if (!noMoreSources && active < maxConcurrency && !sources.IsEmpty)
                        {

                            if (sources.TryDequeue(out var v))
                            {
                                var src = default(ISingleSource<R>);
                                try
                                {
                                    src = RequireNonNullRef(mapper(v), "The mapper returned a null ISingleSource");
                                }
                                catch (Exception ex)
                                {
                                    if (delayErrors)
                                    {
                                        ExceptionHelper.AddException(ref errors, ex);
                                        Volatile.Write(ref done, true);

                                    }
                                    else
                                    {
                                        Interlocked.CompareExchange(ref errors, ex, null);
                                    }
                                    noMoreSources = true;
                                    DisposableHelper.Dispose(ref upstream);
                                    continue;
                                }

                                active++;

                                SubscribeTo(src);
                                continue;
                            }
                        }

                        var d = Volatile.Read(ref done) && sources.IsEmpty;
                        var empty = !observers.TryPeek(out var inner);

                        if (d && empty)
                        {
                            Volatile.Write(ref disposed, true);
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                downstream.OnError(ex);
                            }
                            else
                            {
                                downstream.OnCompleted();
                            }
                            DisposableHelper.Dispose(ref upstream);
                        }
                        else
                        if (!empty)
                        {
                            var state = inner.GetState();

                            if (state == 1)
                            {
                                downstream.OnNext(inner.value);
                                observers.TryDequeue(out var _);
                                active--;
                                continue;
                            }
                            else
                            if (state == 2)
                            {
                                observers.TryDequeue(out var _);
                                active--;
                                continue;
                            }
                        }
                    }

                    missed = Interlocked.Add(ref wip, -missed);
                    if (missed == 0)
                    {
                        break;
                    }
                }
            }

19 View Source File : SingleFlatMapMany.cs
License : Apache License 2.0
Project Creator : akarnokd

internal override void DrainLoop()
            {
                var missed = 1;

                var sources = this.sources;
                var downstream = this.downstream;
                var maxConcurrency = this.maxConcurrency;

                for (; ; )
                {
                    if (IsDisposed())
                    {
                        while (sources.TryDequeue(out var _)) ;
                    }
                    else
                    {
                        if (!delayErrors)
                        {
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                Dispose();
                                downstream.OnError(ex);
                                continue;
                            }
                        }

                        var d = Volatile.Read(ref done);
                        var running = Volatile.Read(ref active);

                        if (!noMoreSources && running < maxConcurrency)
                        {

                            var src = default(ISingleSource<R>);
                            var has = sources.TryDequeue(out var t);

                            if (has)
                            {
                                try
                                {
                                    src = RequireNonNullRef(mapper(t), "The mapper returned a null ISingleSource");
                                }
                                catch (Exception ex)
                                {
                                    if (delayErrors)
                                    {
                                        ExceptionHelper.AddException(ref errors, ex);
                                    }
                                    else
                                    {
                                        Interlocked.CompareExchange(ref errors, ex, null);
                                    }
                                    noMoreSources = true;
                                    Volatile.Write(ref done, true);
                                }

                                if (!noMoreSources)
                                {
                                    Interlocked.Increment(ref active);

                                    SubscribeTo(src);
                                }
                                continue;
                            }
                            else
                            {
                                if (d)
                                {
                                    noMoreSources = true;
                                }
                            }
                        }

                        var q = GetQueue();

                        var v = default(R);

                        var empty = q == null || !q.TryDequeue(out v);

                        if (d && running == 0 && noMoreSources && empty)
                        {
                            Volatile.Write(ref disposed, true);
                            var ex = Volatile.Read(ref errors);
                            if (ex != null)
                            {
                                downstream.OnError(ex);
                            }
                            else
                            {
                                downstream.OnCompleted();
                            }
                        }
                        else
                        if (!empty)
                        {
                            downstream.OnNext(v);
                            continue;
                        }
                    }

                    missed = Interlocked.Add(ref wip, -missed);
                    if (missed == 0)
                    {
                        break;
                    }
                }
            }

19 View Source File : FlowableArray.cs
License : Apache License 2.0
Project Creator : akarnokd

public void Request(long n)
            {
                if (n <= 0L)
                {
                    throw new ArgumentOutOfRangeException(nameof(n));
                }
                if (SubscriptionHelper.AddRequest(ref requested, n) == 0)
                {
                    int idx = index;
                    T[] array = this.array;
                    int f = array.Length;
                    long e = 0;
                    IFlowableSubscriber<T> a = actual;

                    for (;;)
                    {

                        while (idx != f && e != n)
                        {
                            if (Volatile.Read(ref cancelled))
                            {
                                return;
                            }

                            T v = array[idx];

                            if (v == null)
                            {
                                a.OnError(new NullReferenceException("An array item was null"));
                                return;
                            }

                            a.OnNext(v);

                            idx++;
                            e++;
                        }

                        if (idx == f)
                        {
                            if (!Volatile.Read(ref cancelled))
                            {
                                a.OnComplete();
                            }
                            return;
                        }

                        n = Volatile.Read(ref requested);
                        if (e == n)
                        {
                            index = idx;
                            n = Interlocked.Add(ref requested, -n);
                            if (n == 0L)
                            {
                                break;
                            }
                            e = 0L;
                        }
                    }
                }
            }

19 View Source File : FlowableRange.cs
License : Apache License 2.0
Project Creator : akarnokd

public void Request(long n)
            {
                if (n <= 0L)
                {
                    throw new ArgumentOutOfRangeException(nameof(n));
                }
                if (SubscriptionHelper.AddRequest(ref requested, n) == 0)
                {
                    int idx = index;
                    int f = end;
                    long e = 0;
                    IFlowableSubscriber<int> a = actual;

                    for (;;)
                    {

                        while (idx != f && e != n)
                        {
                            if (Volatile.Read(ref cancelled))
                            {
                                return;
                            }

                            a.OnNext(idx);

                            idx++;
                            e++;
                        }

                        if (idx == f)
                        {
                            if (!Volatile.Read(ref cancelled))
                            {
                                a.OnComplete();
                            }
                            return;
                        }

                        n = Volatile.Read(ref requested);
                        if (e == n)
                        {
                            index = idx;
                            n = Interlocked.Add(ref requested, -n);
                            if (n == 0L)
                            {
                                break;
                            }
                            e = 0L;
                        }
                    }
                }
            }

19 View Source File : FlowableRange.cs
License : Apache License 2.0
Project Creator : akarnokd

public void Request(long n)
            {
                if (n <= 0L)
                {
                    throw new ArgumentOutOfRangeException(nameof(n));
                }
                if (SubscriptionHelper.AddRequest(ref requested, n) == 0)
                {
                    int idx = index;
                    int f = end;
                    long e = 0;
                    IConditionalSubscriber<int> a = actual;

                    for (;;)
                    {

                        while (idx != f && e != n)
                        {
                            if (Volatile.Read(ref cancelled))
                            {
                                return;
                            }

                            if (a.TryOnNext(idx))
                            {
                                e++;
                            }

                            idx++;
                        }

                        if (idx == f)
                        {
                            if (!Volatile.Read(ref cancelled))
                            {
                                a.OnComplete();
                            }
                            return;
                        }

                        n = Volatile.Read(ref requested);
                        if (e == n)
                        {
                            index = idx;
                            n = Interlocked.Add(ref requested, -n);
                            if (n == 0L)
                            {
                                break;
                            }
                            e = 0L;
                        }
                    }
                }
            }

19 View Source File : FlowableArray.cs
License : Apache License 2.0
Project Creator : akarnokd

public void Request(long n)
            {
                if (n <= 0L)
                {
                    throw new ArgumentOutOfRangeException(nameof(n));
                }
                if (SubscriptionHelper.AddRequest(ref requested, n) == 0)
                {
                    int idx = index;
                    T[] array = this.array;
                    int f = array.Length;
                    long e = 0;
                    IConditionalSubscriber<T> a = actual;

                    for (;;)
                    {

                        while (idx != f && e != n)
                        {
                            if (Volatile.Read(ref cancelled))
                            {
                                return;
                            }

                            T v = array[idx];

                            if (v == null)
                            {
                                a.OnError(new NullReferenceException("An array item was null"));
                                return;
                            }

                            if (a.TryOnNext(v))
                            {
                                e++;
                            }

                            idx++;
                        }

                        if (idx == f)
                        {
                            if (!Volatile.Read(ref cancelled))
                            {
                                a.OnComplete();
                            }
                            return;
                        }

                        n = Volatile.Read(ref requested);
                        if (e == n)
                        {
                            index = idx;
                            n = Interlocked.Add(ref requested, -n);
                            if (n == 0L)
                            {
                                break;
                            }
                            e = 0L;
                        }
                    }
                }
            }

19 View Source File : FlowableEnumerable.cs
License : Apache License 2.0
Project Creator : akarnokd

protected override void OnRequest(long n)
            {
                IFlowableSubscriber<T> a = actual;
                IEnumerator<T> en = enumerator;
                long e = 0L;

                for (;;)
                {
                    while (e != n)
                    {
                        if (Volatile.Read(ref cancelled) != 0)
                        {
                            Clear();
                            return;
                        }

                        T v = en.Current;
                        if (v == null)
                        {
                            Clear();
                            a.OnError(new NullReferenceException("One of the IEnumerator items is null"));
                            return;
                        }

                        a.OnNext(v);

                        bool b;

                        try
                        {
                            b = en.MoveNext();
                        }
                        catch (Exception ex)
                        {
                            Clear();
                            a.OnError(ex);
                            return;
                        }

                        if (!b)
                        {
                            Clear();
                            if (Volatile.Read(ref cancelled) == 0)
                            {
                                a.OnComplete();
                            }
                            return;
                        }

                        e++;
                    }

                    n = Volatile.Read(ref requested);
                    if (e == n)
                    {
                        n = Interlocked.Add(ref requested, -n);
                        if (n == 0L)
                        {
                            break;
                        }
                        e = 0L;
                    }
                }
            }

19 View Source File : FlowableEnumerable.cs
License : Apache License 2.0
Project Creator : akarnokd

protected override void OnRequest(long n)
            {
                IConditionalSubscriber<T> a = actual;
                IEnumerator<T> en = enumerator;
                long e = 0L;

                for (;;)
                {
                    while (e != n)
                    {
                        if (Volatile.Read(ref cancelled) != 0)
                        {
                            Clear();
                            return;
                        }

                        T v = en.Current;
                        if (v == null)
                        {
                            Clear();
                            a.OnError(new NullReferenceException("One of the IEnumerator items is null"));
                            return;
                        }

                        if (a.TryOnNext(v))
                        {
                            e++;
                        }

                        bool b;

                        try
                        {
                            b = en.MoveNext();
                        }
                        catch (Exception ex)
                        {
                            Clear();
                            a.OnError(ex);
                            return;
                        }

                        if (!b)
                        {
                            Clear();
                            if (Volatile.Read(ref cancelled) == 0)
                            {
                                a.OnComplete();
                            }
                            return;
                        }
                    }

                    n = Volatile.Read(ref requested);
                    if (e == n)
                    {
                        n = Interlocked.Add(ref requested, -n);
                        if (n == 0L)
                        {
                            break;
                        }
                        e = 0L;
                    }
                }
            }

19 View Source File : FlowableGenerate.cs
License : Apache License 2.0
Project Creator : akarnokd

void Drain(long n)
            {
                var s = state;
                var g = emitter;
                var a = actual;
                for (;;)
                {
                    long e = 0L;
                    while (e != n)
                    {
                        if (Volatile.Read(ref cancelled))
                        {
                            CleanupAfter(s);
                            return;
                        }

                        try
                        {
                            s = emitter(s, this);
                        }
                        catch (Exception exc)
                        {
                            if (error == null)
                            {
                                error = exc;
                            }
                            done = true;
                        }

                        if (hasValue)
                        {
                            hasValue = false;
                            var v = value;
                            value = default(T);
                            a.OnNext(v);
                            e++;
                        }
                        else
                        if (!done)
                        {
                            var m = new InvalidOperationException("OnNext() not called");
                            var ex = error;
                            if (ex == null)
                            {
                                ex = m;
                            }
                            else
                            {
                                ex = new AggregateException(ex, m);
                            }
                            done = true;
                        }

                        if (done)
                        {
                            var ex = error;
                            if (ex != null)
                            {
                                if (eager)
                                {
                                    try
                                    {
                                        if (Interlocked.CompareExchange(ref once, 1, 0) == 0)
                                        {
                                            stateCleanup?.Invoke(state);
                                        }
                                    }
                                    catch (Exception ex2)
                                    {
                                        ex = new AggregateException(ex, ex2);
                                    }
                                }
                                a.OnError(ex);
                            }
                            else
                            {
                                if (eager)
                                {
                                    try
                                    {
                                        if (Interlocked.CompareExchange(ref once, 1, 0) == 0)
                                        {
                                            stateCleanup?.Invoke(state);
                                        }
                                    }
                                    catch (Exception ex2)
                                    {
                                        a.OnError(ex2);
                                        return;
                                    }
                                }
                                a.OnComplete();
                            }
                            if (!eager)
                            {
                                CleanupAfter(s);
                            }
                            return;
                        }
                    }

                    n = Volatile.Read(ref requested);
                    if (e == n)
                    {
                        state = s;
                        n = Interlocked.Add(ref requested, -n);
                        if (n == 0L)
                        {
                            break;
                        }
                    }
                }
            }

19 View Source File : SubscriptionArbiter.cs
License : Apache License 2.0
Project Creator : akarnokd

public void ArbiterProduced(long n)
        {
            if (n <= 0L)
            {
                throw new ArgumentOutOfRangeException(nameof(n));
            }
            if (Volatile.Read(ref wip) == 0 && Interlocked.CompareExchange(ref wip, 1, 0) == 0)
            {
                var r = requested;
                if (r != long.MaxValue)
                {
                    long u = r - n;
                    if (u < 0)
                    {
                        u = 0;
                    }
                    requested = u;
                }
                if (Interlocked.Decrement(ref wip) == 0)
                {
                    return;
                }
            }
            else
            {
                Interlocked.Add(ref missedProduced, n);
                if (Interlocked.Increment(ref wip) != 1)
                {
                    return;
                }
            }
            ArbiterDrainLoop();
        }

19 View Source File : FlowableRepeatItem.cs
License : Apache License 2.0
Project Creator : akarnokd

protected override void OnRequest(long n)
            {
                long e = 0L;
                var a = actual;
                var v = item;

                for (;;)
                {
                    while (e != n)
                    {
                        if (Volatile.Read(ref cancelled))
                        {
                            return;
                        }

                        a.OnNext(v);

                        e++;
                    }

                    n = Volatile.Read(ref requested);
                    if (e == n)
                    {
                        n = Interlocked.Add(ref requested, -e);
                        if (n == 0L)
                        {
                            break;
                        }
                        e = 0L;
                    }
                }
            }

19 View Source File : FlowableRepeatItem.cs
License : Apache License 2.0
Project Creator : akarnokd

protected override void OnRequest(long n)
            {
                long e = 0L;
                var a = actual;
                var v = item;

                for (;;)
                {
                    while (e != n)
                    {
                        if (Volatile.Read(ref cancelled))
                        {
                            return;
                        }

                        if (a.TryOnNext(v))
                        {
                            e++;
                        }
                    }

                    n = Volatile.Read(ref requested);
                    if (e == n)
                    {
                        n = Interlocked.Add(ref requested, -e);
                        if (n == 0L)
                        {
                            break;
                        }
                        e = 0L;
                    }
                }
            }

19 View Source File : FlowableRepeatFunction.cs
License : Apache License 2.0
Project Creator : akarnokd

protected override void OnRequest(long n)
            {
                long e = 0L;
                var a = actual;
                var f = func;

                for (;;)
                {
                    while (e != n)
                    {
                        if (Volatile.Read(ref cancelled))
                        {
                            return;
                        }

                        T v;

                        try
                        {
                            v = func();
                        }
                        catch (Exception ex)
                        {
                            cleared = true;
                            a.OnError(ex);
                            return;
                        }

                        a.OnNext(v);

                        e++;
                    }

                    n = Volatile.Read(ref requested);
                    if (e == n)
                    {
                        n = Interlocked.Add(ref requested, -e);
                        if (n == 0L)
                        {
                            break;
                        }
                        e = 0L;
                    }
                }
            }

19 View Source File : FlowableRepeatFunction.cs
License : Apache License 2.0
Project Creator : akarnokd

protected override void OnRequest(long n)
            {
                long e = 0L;
                var a = actual;
                var f = func;

                for (;;)
                {
                    while (e != n)
                    {
                        if (Volatile.Read(ref cancelled))
                        {
                            return;
                        }

                        T v;

                        try
                        {
                            v = func();
                        }
                        catch (Exception ex)
                        {
                            cleared = true;
                            a.OnError(ex);
                            return;
                        }

                        if (a.TryOnNext(v))
                        {

                            e++;
                        }
                    }

                    n = Volatile.Read(ref requested);
                    if (e == n)
                    {
                        n = Interlocked.Add(ref requested, -e);
                        if (n == 0L)
                        {
                            break;
                        }
                        e = 0L;
                    }
                }
            }

19 View Source File : BlockingQueueConsumer.cs
License : Apache License 2.0
Project Creator : akarnokd

internal void Run()
        {
            Thread.CurrentThread.IsBackground = daemon;
            var n = name;
            if (n != null)
            {
                try 
                { 
                    Thread.CurrentThread.Name = n;
                }
                catch (InvalidOperationException)
                {
                    // ignored
                }
            }
            var sh = ShutdownAction;
            var q = queue;
            long missed = 0L;
            for (;;)
            {
                if (Volatile.Read(ref shutdown) != 0)
                {
                    q.Clear();
                    break;
                }
                Action a = null;

                for (int i = 0; i < 64; i++)
                {
                    if (q.Poll(out a))
                    {
                        break;
                    }
                }

                if (a != null)
                {
                    if (a == sh)
                    {
                        q.Clear();
                        break;
                    }
                    try
                    {
                        a();
                    }
                    catch
                    {
                        // TODO what to do with these?
                    }
                }
                else
                {
                    long w = Volatile.Read(ref wip);
                    if (w == missed)
                    {
                        missed = Interlocked.Add(ref wip, -missed);
                        if (missed == 0)
                        {
                            if (Monitor.TryEnter(this))
                            {
                                try
                                {
                                    while ((missed = Volatile.Read(ref wip)) == 0)
                                    {
                                        Monitor.Wait(this);
                                    }
                                }
                                finally
                                {
                                    Monitor.Exit(this);
                                }
                            }
                        }
                    }
                    else
                    {
                        missed = w;
                    }
                }
            }
        }

19 View Source File : TrampolineExecutorService.cs
License : Apache License 2.0
Project Creator : akarnokd

void Drain()
            {
                if (Interlocked.Increment(ref wip) != 1L)
                {
                    return;
                }

                var q = queue;
                long missed = 1L;
                for (;;)
                {
                    while (q.Poll(out InterruptibleAction a))
                    {
                        if (Volatile.Read(ref cancelled) != 0)
                        {
                            try
                            {
                                a.Run();
                            }
                            catch
                            {
                                // TODO what to do with these?
                            }
                        }
                    }
                    long w = Volatile.Read(ref wip);
                    if  (w == missed)
                    {
                        missed = Interlocked.Add(ref wip, -missed);
                        if (missed == 0L)
                        {
                            break;
                        }
                    }
                    else
                    {
                        missed = w;
                    }
                }
            }

19 View Source File : SubscriptionHelper.cs
License : Apache License 2.0
Project Creator : akarnokd

static void PostCompleteMultiDrain<T>(IFlowableSubscriber<T> actual, ref long requested, ISimpleQueue<T> q, ref bool cancelled)
        {
            long r = Volatile.Read(ref requested);
            long e = long.MinValue;
            for (;;)
            {
                while (e != r)
                {
                    if (Volatile.Read(ref cancelled))
                    {
                        return;
                    }

                    bool empty = !q.Poll(out T v);

                    if (empty)
                    {
                        actual.OnComplete();
                        return;
                    }

                    actual.OnNext(v);

                    e++;
                }

                if (e == r)
                {
                    if (Volatile.Read(ref cancelled))
                    {
                        return;
                    }
                    if (q.IsEmpty())
                    {
                        actual.OnComplete();
                        return;
                    }
                }

                r = Volatile.Read(ref requested);
                if (r == e)
                {
                    r = Interlocked.Add(ref requested, -(e & long.MaxValue));
                    
                    if (r == long.MinValue)
                    {
                        break;
                    }
                    e = long.MinValue;
                }
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : altimesh

[EntryPoint]
        public static void ReduceAdd(int N, int[] a, int[] result)
        {
            var cache = new SharedMemoryAllocator<int>().allocate(blockDim.x);
            int tid = threadIdx.x + blockDim.x * blockIdx.x;
            int cacheIndex = threadIdx.x;

            int tmp = 0;
            while (tid < N)
            {
                tmp += a[tid];
                tid += blockDim.x * gridDim.x;
            }

            cache[cacheIndex] = tmp;

            CUDAIntrinsics.__syncthreads();

            int i = blockDim.x / 2;
            while (i != 0)
            {
                if (cacheIndex < i)
                {
                    cache[cacheIndex] += cache[cacheIndex + i];
                }

                CUDAIntrinsics.__syncthreads();
                i >>= 1;
            }

            if (cacheIndex == 0)
            {
                Interlocked.Add(ref result[0], cache[0]);
            }
        }

19 View Source File : RuntimeGuard.cs
License : MIT License
Project Creator : ashmind

private void EnsureCount(long count) {
            Interlocked.Add(ref _allocatedCountTotal, count);
            if (_allocatedCountTotal > _allocatedCountTotalLimit)
                throw new MemoryGuardException();
        }

19 View Source File : AsyncCloudWatchLogsSink.cs
License : Apache License 2.0
Project Creator : awslabs

private async Task ProcessingTask(CancellationToken stopToken)
        {
            var events = new List<Envelope<InputLogEvent>>();

            while (!stopToken.IsCancellationRequested)
            {
                try
                {
                    if (events.Count == 0)
                    {
                        await _queue.GetNextBatchAsync(events, _bufferIntervalMs, stopToken);
                        events.Sort((r1, r2) => r1.Timestamp.CompareTo(r2.Timestamp));
                    }

                    RemoveEmptyRecords(events);

                    await ThrottleAsync(events, stopToken);

                    await SendBatchAsync(events, stopToken);
                    PublishMetrics(MetricsConstants.CLOUDWATCHLOG_PREFIX);
                }
                catch (OperationCanceledException) when (stopToken.IsCancellationRequested)
                {
                    break;
                }
                catch (Exception ex)
                {
                    _throttle.SetError();

                    if (IsRecoverableException(ex))
                    {
                        _logger.LogWarning("Encountered recoverable error of type {0}", ex.GetType());
                        Interlocked.Increment(ref _recoverableServiceErrors);
                        Interlocked.Add(ref _recordsFailedRecoverable, events.Count);

                        if (_throttle.ConsecutiveErrorCount > _maxAttempts && _queue.HreplacedecondaryQueue())
                        {
                            // Re-queue into the secondary queue when we've reached attempt limits
                            // This means that records will be out of order
                            _logger.LogDebug("Requeueing to secondary queue");
                            await _queue.PushSecondaryAsync(events);
                            events.Clear();
                        }
                        continue;
                    }

                    _logger.LogError(ex, "Error sending events (attempt={0})", _throttle.ConsecutiveErrorCount);
                    Interlocked.Increment(ref _nonrecoverableServiceErrors);
                    Interlocked.Add(ref _recordsFailedNonrecoverable, events.Count);
                    events.Clear();
                    continue;
                }
            }
        }

19 View Source File : AsyncCloudWatchLogsSink.cs
License : Apache License 2.0
Project Creator : awslabs

private async Task SendBatchAsync(List<Envelope<InputLogEvent>> records, CancellationToken stopToken)
        {
            if (records.Count == 0)
            {
                return;
            }

            var logStreamName = ResolveTimestampInLogStreamName(records[0].Timestamp);
            var batchBytes = records.Sum(r => GetRecordSize(r));

            Interlocked.Add(ref _recordsAttempted, records.Count);
            Interlocked.Add(ref _bytesAttempted, batchBytes);
            Interlocked.Exchange(ref _clientLatency, (long)records.Average(r => (DateTime.UtcNow - r.Timestamp).TotalMilliseconds));

            _logger.LogDebug("Sending {0} records {1} bytes.", records.Count, batchBytes);

            var sendCount = 0;
            if (records[records.Count - 1].Timestamp - records[0].Timestamp <= _batchMaximumTimeSpan)
            {
                sendCount = records.Count;
            }
            else
            {
                while (sendCount < records.Count && records[sendCount].Timestamp - records[0].Timestamp <= _batchMaximumTimeSpan)
                {
                    sendCount++;
                }
            }

            var recordsToSend = records.Take(sendCount).Select(e => e.Data).ToList();
            var beforeSendTimestamp = Utility.GetElapsedMilliseconds();

            // If the sequence token is null, try to get it.
            // If the log stream doesn't exist, create it (by specifying "true" in the second parameter).
            // This should be the only place where a log stream is created.
            // This method will ensure that both the log group and stream exists,
            // so there is no need to handle a ResourceNotFound exception later.
            if (string.IsNullOrEmpty(_sequenceToken) || AWSConstants.NullString.Equals(_sequenceToken))
            {
                await GetSequenceTokenAsync(logStreamName, true, stopToken);
            }

            var request = new PutLogEventsRequest
            {
                LogGroupName = _logGroup,
                LogStreamName = logStreamName,
                SequenceToken = _sequenceToken,
                LogEvents = recordsToSend
            };

            try
            {
                // try sending the records and mark them as sent
                var response = await _cloudWatchLogsClient.PutLogEventsAsync(request, stopToken);
                Interlocked.Exchange(ref _latency, Utility.GetElapsedMilliseconds() - beforeSendTimestamp);

                // update sequence token
                _sequenceToken = response.NextSequenceToken;

                var recordsSent = recordsToSend.Count;
                var rejectedLogEventsInfo = response.RejectedLogEventsInfo;
                if (rejectedLogEventsInfo is not null)
                {
                    var sb = new StringBuilder()
                        .Append("CloudWatchLogsSink encountered some rejected logs.")
                        .AppendFormat(" ExpiredLogEventEndIndex {0}", rejectedLogEventsInfo.ExpiredLogEventEndIndex)
                        .AppendFormat(" TooNewLogEventStartIndex {0}", rejectedLogEventsInfo.TooNewLogEventStartIndex)
                        .AppendFormat(" TooOldLogEventEndIndex {0}", rejectedLogEventsInfo.TooOldLogEventEndIndex);
                    _logger.LogWarning(sb.ToString());
                    if (rejectedLogEventsInfo.TooNewLogEventStartIndex >= 0)
                    {
                        recordsSent -= recordsToSend.Count - rejectedLogEventsInfo.TooNewLogEventStartIndex;
                    }
                    var tooOldIndex = Math.Max(rejectedLogEventsInfo.TooNewLogEventStartIndex, rejectedLogEventsInfo.ExpiredLogEventEndIndex);
                    if (tooOldIndex > 0)
                    {
                        recordsSent -= tooOldIndex;
                    }
                    if (recordsSent < 0)
                    {
                        recordsSent = 0;
                    }
                }


                Interlocked.Add(ref _recordsSuccess, recordsSent);
                Interlocked.Add(ref _recordsFailedNonrecoverable, recordsToSend.Count - recordsSent);
                _logger.LogDebug("Successfully sent {0} records.", recordsSent);

                // save the bookmarks only for the records that were processed
                await SaveBookmarksAsync(records.Take(sendCount).ToList());

                records.RemoveRange(0, sendCount);
            }
            catch (AmazonCloudWatchLogsException acle)
            {
                Interlocked.Exchange(ref _latency, Utility.GetElapsedMilliseconds() - beforeSendTimestamp);

                // handle the types of exceptions we know how to handle
                // then return so that the records can be re-sent
                switch (acle)
                {
                    case InvalidSequenceTokenException iste:
                        _sequenceToken = iste.ExpectedSequenceToken;
                        break;
                    case ResourceNotFoundException:
                        await GetSequenceTokenAsync(logStreamName, true, stopToken);
                        break;
                    case DataAlreadyAcceptedException:
                        // this batch won't be accepted, skip it
                        await SaveBookmarksAsync(records.Take(sendCount).ToList());
                        records.RemoveRange(0, sendCount);
                        break;
                    case InvalidParameterException ipme:
                        // this can happens due to a log event being too large
                        // we already checked for this when creating the record,
                        // so best thing we can do here is to skip this batch and moveon
                        _logger.LogError(ipme, "Error sending records to CloudWatchLogs");
                        records.RemoveRange(0, sendCount);
                        break;
                    default:
                        // for other exceptions we rethrow so the main loop can catch it
                        throw;

                }
            }
        }

19 View Source File : CappedQueue.cs
License : MIT License
Project Creator : azist

public bool TryEnqueue(T item)
    {
      var maxCount = CountLimit;
      var maxSize = SizeLimit;

      if (
           (maxCount > 0 && Thread.VolatileRead(ref m_EnqueuedCount) >= maxCount) ||
           (maxSize > 0 && Thread.VolatileRead(ref m_EnqueuedSize) >= maxSize)
         )
      {
        if (Handling == QueueLimitHandling.DiscardOld)
          trimOldExcess();
        else if (Handling == QueueLimitHandling.Throw)
          throw new AzosException(StringConsts.COLLECTION_CAPPED_QUEUE_LIMIT_ERROR.Args(nameof(CappedQueue<T>), Handling));
        else return false;//DiscardNew
      }

      var sz = m_GereplacedemSize(item);
      Interlocked.Increment(ref m_EnqueuedCount);
      Interlocked.Add(ref m_EnqueuedSize, sz);

      m_Data.Enqueue(item);
      return true;
    }

19 View Source File : CappedQueue.cs
License : MIT License
Project Creator : azist

public bool TryDequeue(out T item)
    {
      var result = m_Data.TryDequeue(out item);
      if (result)
      {
        var sz = m_GereplacedemSize(item);
        Interlocked.Decrement(ref m_EnqueuedCount);
        Interlocked.Add(ref m_EnqueuedSize, -sz);
      }
      return result;
    }

19 View Source File : CappedQueue.cs
License : MIT License
Project Creator : azist

private void trimOldExcess()
    {
      var maxCount = CountLimit;
      var maxSize = SizeLimit;

      for (var i = 0; i < MAX_ITERATIONS &&
              (
                (maxCount > 0 && Thread.VolatileRead(ref m_EnqueuedCount) >= maxCount) ||
                (maxSize > 0 && Thread.VolatileRead(ref m_EnqueuedSize) >= maxSize)
              );
              i++
          )
      {
        if (!m_Data.TryDequeue(out var discarded)) break;
        var sz = m_GereplacedemSize(discarded);
        Interlocked.Decrement(ref m_EnqueuedCount);
        Interlocked.Add(ref m_EnqueuedSize, -sz);

        m_DiscardedItem?.Invoke(discarded);
      }
    }

19 View Source File : NamedInterlocked.cs
License : MIT License
Project Creator : azist

public long AddLong(string name, long arg)
    {
      var slot = getSlot(name);
      return Interlocked.Add(ref slot.Long, arg);
    }

19 View Source File : NamedInterlocked.cs
License : MIT License
Project Creator : azist

public Amount Add(Amount arg)
    {
      var slot = getSlot(arg.ISO.Value);
      return new Amount(arg.ISO, Interlocked.Add(ref slot.Long, convertDecimalToLong(arg.Value)));
    }

19 View Source File : FileObjectStoreProvider.cs
License : MIT License
Project Creator : azist

private ObjectStoreEntry readFile(string fname, ISerializer serializer, DateTime now, ref long priorLoadSize, Stopwatch clock)
    {
      using (var fs = new FileStream(fname, FileMode.Open))//, FileAccess.Read, FileShare.Read, 64*1024, FileOptions.SequentialScan))
      {

        var entry = new ObjectStoreEntry();
        try
        {
          entry.Value = serializer.Deserialize(fs);
        }
        catch (Exception error)
        {
          WriteLog(MessageType.Error, FROM, "Deserialization error in file '{0}': {1}".Args(fname, error.Message));
          return null;
        }

        Interlocked.Add(ref m_LoadSize, fs.Length);

        if (m_LoadSize - priorLoadSize > 32 * 1024 * 1024)
        {
          WriteLog(MessageType.Info, FROM, "Loaded disk bytes {0} in {1}".Args(LoadSize, clock.Elapsed));
          priorLoadSize = m_LoadSize;
        }

        entry.Key = getGUIDFromFileName(fname);
        entry.LastTime = now;
        entry.Status = ObjectStoreEntryStatus.Normal;

        return entry;
      }
    }

19 View Source File : Transport.cs
License : MIT License
Project Creator : azist

protected internal void stat_BytesReceived(long val) { Interlocked.Add(ref m_StatBytesReceived, val); }

19 View Source File : Transport.cs
License : MIT License
Project Creator : azist

protected internal void stat_BytesSent(long val) { Interlocked.Add(ref m_StatBytesSent, val); }

19 View Source File : Transport.cs
License : MIT License
Project Creator : azist

protected internal void stat_MsgReceived(long count = 1) { Interlocked.Add(ref m_StatMsgReceived, count); m_ExpirationStart = null; }

19 View Source File : LocalCacheTable.cs
License : MIT License
Project Creator : azist

public void sweep()
                     {
                       var i = m_IdxSweep * ONE_SWEEP;

                       if (i>=Entries.Length)
                       {
                         while(m_LastSweeps.Count-1>m_IdxSweep) m_LastSweeps.RemoveAt(m_LastSweeps.Count-1);
                         m_IdxSweep = 0;
                         i = 0;
                       }

                       var pile = Table.m_Cache.m_Pile;
                       var now = Ambient.UTCNow;

                       var elapsedSec = 0;
                       if (m_IdxSweep==m_LastSweeps.Count)
                        m_LastSweeps.Add(now);
                       else
                       {
                         elapsedSec = (int)(now - m_LastSweeps[m_IdxSweep]).TotalSeconds;
                         m_LastSweeps[m_IdxSweep] = now;
                       }

                       m_IdxSweep++;

                       var deleted = 0;
                       for(var cnt = 0; cnt<ONE_SWEEP && i<Entries.Length; i++, cnt++)
                       {
                         var entry = Entries[i];
                         var expired = false;
                         if (!entry.DataPointer.Valid) continue;//already blank

                         if (entry.IsChain)
                         {
                                var chain = pile.Get( entry.DataPointer ) as _chain;
                                var mutated = false;
                                for(var j=0; j<chain.Links.Count;)
                                {
                                  var clentry = chain.Links[j];
                                  if (clentry.MaxAgeSec>0)
                                  {
                                    clentry.AgeSec += elapsedSec;
                                    if (clentry.AgeSec > clentry.MaxAgeSec)
                                      expired = true;
                                    else
                                    {
                                      chain.Links[j] = clentry;
                                      mutated = true;
                                    }
                                  }

                                  if (expired || (clentry.ExpirationUTC.Ticks!=0 && now >= clentry.ExpirationUTC))
                                  {
                                    pile.Delete( clentry.DataPointer, throwInvalid: false );
                                    chain.Links.RemoveAt(j);
                                    deleted++;
                                    mutated = true;
                                  }
                                  else j++;
                                }//for all chain links

                                if (mutated || chain.Links.Count==0)
                                {
                                  pile.Delete( entry.DataPointer, throwInvalid: false );
                                  if (chain.Links.Count>0)
                                  {
                                    entry.DataPointer = Table.m_Cache.m_Pile.Put( chain );
                                    Entries[i] = entry;
                                  }
                                  else
                                  {
                                    Entries[i] = _entry.Empty;
                                  }
                                }
                            continue;
                         }//chain


                         //non-chain ----------------------------------
                         if (entry.MaxAgeSec>0)
                         {
                           entry.AgeSec += elapsedSec;
                           if (entry.AgeSec > entry.MaxAgeSec)
                             expired = true;
                           else
                             Entries[i].AgeSec = entry.AgeSec;
                         }

                         if (expired || (entry.ExpirationUTC.Ticks!=0 && now >= entry.ExpirationUTC))
                         {
                           pile.Delete( entry.DataPointer, throwInvalid: false );
                           Entries[i] = _entry.Empty;
                           deleted++;
                         }
                       }//for i


                       this.COUNT-=deleted;
                       shrinkIfNeeded();

                       Interlocked.Add(ref Table.m_stat_Sweep, deleted);
                     }

19 View Source File : LockServerService.cs
License : MIT License
Project Creator : azist

private void removeExpiredTableData(DateTime now)
    {
      long totalRemoved = 0;
      foreach( var ns in m_Namespaces)//thread-safe snapshot
      {
        if (!Running) return;

        lock(ns)
        {
          foreach(var tbl in ns.Tables)
          {
            if (!Running) return;

            totalRemoved += tbl.RemoveExpired( now );

            if (ns.RemoveTableIfEmpty( tbl ))//does not affect the foreach as it is snapshot based
              if (m_InstrumentationEnabled)
              Interlocked.Increment(ref m_stat_RemovedEmptyTables);
          }
        }
      }


      if (m_InstrumentationEnabled)
        Interlocked.Add(ref m_stat_ExpiredRecords, totalRemoved);
    }

19 View Source File : CmsFacade.cs
License : MIT License
Project Creator : azist

private void expireCache()
    {
      var span = CacheSpanSec;
      if (span == 0) span = DEFAULT_CACHE_SEC;

      var countTotal = 0;
      var countDeleted = 0;
      var now = App.TimeSource.UTCNow;
      foreach(var dict in m_Data)
      {
        lock(dict)//this lock is very fast, we do not do any IO operations under it
        {
          countTotal += dict.Count;

          if (span<0)
          {
            countDeleted += dict.Count;
            dict.Clear();
            continue;
          }

          var toDelete = new List<idiso>();
          foreach(var kvp in dict)
          {
            var sd = kvp.Value.sd;
            if ((now - sd).TotalSeconds > span)
              toDelete.Add(kvp.Key);//mark for deletion
          }

          countDeleted += toDelete.Count;
          foreach (var key in toDelete)
            dict.Remove(key);
        }//lock(dict)
      }

      if (InstrumentationEnabled)
      {
        Interlocked.Add(ref m_stat_CacheRecordCount, countTotal);
        Interlocked.Add(ref m_stat_CacheExpiredRecordCount, countDeleted);
      }
    }

19 View Source File : Response.cs
License : MIT License
Project Creator : azist

protected override void Destructor()
      {
         try
         {
           try
           {
             var srv = Work.Server;
             var ie = srv.m_InstrumentationEnabled;

             if (ie && m_WasWrittenTo)
              Interlocked.Increment(ref srv.m_stat_WorkContextWrittenResponse);

             stowClientVars();

             if (m_Buffer!=null)
             {
                var sz = m_Buffer.Position;
                m_NetResponse.ContentLength64 = sz;
                m_NetResponse.OutputStream.Write(m_Buffer.GetBuffer(), 0, (int)sz);
                m_Buffer = null;

                if (ie)
                {
                  Interlocked.Increment(ref srv.m_stat_WorkContextBufferedResponse);
                  Interlocked.Add(ref srv.m_stat_WorkContextBufferedResponseBytes, sz);
                }
             }
           }
           finally
           {
             m_NetResponse.OutputStream.Close();
 	           m_NetResponse.Close();
           }
         }
         catch(HttpListenerException lerror)
         {
           if (lerror.ErrorCode!=64)//specified net name no longer available
            Work.Log(MessageType.Error, lerror.ToMessageWithType(), "Response.dctor()", lerror);
         }
      }

19 View Source File : WaveForm.cs
License : MIT License
Project Creator : azist

private void threadFunc(object arg)
    {
      var threadArg = arg as ThreadArg;
      var batchItems = threadArg.BatchItems;
      var rawBatches = threadArg.RawBatches;
      var keepAlive = threadArg.KeepAlive;
      int callCnt, errCnt;

      WebClient wc = null;

      for (int iBatch = 0; iBatch < threadArg.CallCnt && m_IsRunning; iBatch++)
      {
        if (iBatch % rawBatches == 0)
        {
          if (wc != null) wc.Dispose();
          wc = this.CreateWebClient(keepAlive);
        }

        errCnt = callCnt = 0;
        foreach (var item in batchItems)
        {
          if (!m_IsRunning) break;
          for (int iItem = 0; iItem < item.Cnt && m_IsRunning; iItem++)
          {
            try
            {
              callCnt++;
              item.Action(wc);
            }
            catch (Exception ex)
            {
              errCnt++;
              LogMsg("Method " + item.Action.Method.Name + " " + ex.Message);
            }
          }
          
        } 
        Interlocked.Add(ref m_CallCnt, callCnt);
        Interlocked.Add(ref m_ErrCnt, errCnt);
      }

      if (wc != null) 
      {
        wc.Dispose();
        wc = null;
      }

      lock (m_ThreadsState)
      {
        m_ThreadsState[System.Threading.Thread.CurrentThread.ManagedThreadId] = false;
        if (m_ThreadsState.Any(ts => ts.Value)) return;

        setControlEnabled(true);
        
        LogMsg("OK={0:n0} ERR={1:n0}".Args(m_CallCnt - m_ErrCnt, m_ErrCnt), true);
        updateCaption();
        m_IsRunning = false;
      }
    }

See More Examples