Esempio n. 1
0
        public void PwmProc()
        {
            // totalCycle = (1/n)*1000 = Total MS for the full cycle
            // onCycle = totalCycle * (DutyCycle / 100)
            // offCycle = totalCycle - onCycle;

            SpinWait  sp = new SpinWait();
            Stopwatch sw = new Stopwatch();

            int totalCycleTicks = (int)((1f / Frequency) * Stopwatch.Frequency);
            int onTicks         = (int)Math.Round(totalCycleTicks * (DutyCycle / 100f));
            int offTicks        = totalCycleTicks - onTicks;

            Debug.WriteLine("On Ticks: " + onTicks);

            while (IsRunning)
            {
                /**** ON ****/
                // Turn the pin on for the duty cycle
                Pin(true);

                // Let the pin stay high until we stop or
                sw.Reset();
                sp.Reset();
                sw.Start();
                while (sw.ElapsedTicks < onTicks)
                {
                    ;
                }
                //sp.SpinOnce();

                //Debug.WriteLine("Total Spin On: " + sw.ElapsedTicks + " and needed " + onTicks);

                /**** OFF ****/
                // Turn the pin off for the rest period
                Pin(false);

                sw.Reset();
                sp.Reset();
                sw.Start();
                while (sw.ElapsedTicks < offTicks)
                {
                    ;
                }
                //sp.SpinOnce();

                //Debug.WriteLine("Total Spin Off: " + sw.ElapsedTicks + " and needed " + offTicks);
            }

            // Turn off the PIN when we're done
            Pin(false);
        }
        void TryDoWork(int index)
        {
            Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId} started do work {index}");
            Interlocked.Decrement(ref _notStartedThreadsCount);
            var spinWait = new SpinWait();

            while (!_isDisposed)
            {
                bool isDeququed = _workItems.TryDequeue(out var callback);
                if (isDeququed)
                {
                    callback(null);
                    continue;
                }

                _mre.Reset();

                if (spinWait.NextSpinWillYield)
                {
                    Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId} WAIT ONE");
                    _mre.WaitOne();
                    spinWait.Reset();
                }
                spinWait.SpinOnce();
            }

            Interlocked.Increment(ref _notStartedThreadsCount);
            Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId} finished do work {index}");
        }
Esempio n. 3
0
        private void DispatchThreadMethod()
        {
            var snipWait = new SpinWait();

            while (!this.StopDispatch)
            {
                if (this.EventQueue.Length == 0)
                {
                    snipWait.SpinOnce();
                }
                else
                {
                    snipWait.Reset();

                    IEvent @event        = this.EventQueue.Dequeue();
                    var    pars          = new Object[] { @event };
                    var    subeventQueue = new PriorityQueue <EventHandleInfo>();

                    if (this.RegisterInfo.TryGetValue(@event.GetType(), out EventRegisterInfo registered))
                    {
                        foreach (EventHandleInfo handle in registered.EventHandleList)
                        {
                            subeventQueue.Add(handle, (Int32)handle.Priority);
                        }

                        while (subeventQueue.Length != 0)
                        {
                            EventHandleInfo handle = subeventQueue.Dequeue();
                            ThreadPool.QueueUserWorkItem(state => handle.Method.Invoke(handle.Instance, pars));
                        }
                    }
                }
            }
        }
    public long Run(ThroughputSessionContext sessionContext)
    {
        _eventHandler.Reset(_iterations - 1);
        _consumer.Start();

        sessionContext.Start();

        var spinWait = new SpinWait();

        for (long i = 0; i < _iterations; i++)
        {
            var data = new PerfEvent {
                Value = i
            };
            while (_queue.Count == _bufferSize)
            {
                spinWait.SpinOnce();
            }
            _queue.Enqueue(data);
            spinWait.Reset();
        }

        _eventHandler.WaitForSequence();
        sessionContext.Stop();
        _consumer.Stop();

        sessionContext.SetBatchData(_eventHandler.BatchesProcessed, _iterations);

        PerfTestUtil.FailIfNot(_expectedResult, _eventHandler.Value, $"Handler should have processed {_expectedResult} events, but was: {_eventHandler.Value}");

        return(_iterations);
    }
        public void Start()
        {
            var started = new ManualResetEventSlim();

            _running = true;
            _task    = Task.Run(() =>
            {
                started.Set();

                var spinWait = new SpinWait();
                while (true)
                {
                    PerfEvent perfEvent;

                    while (!_queue.TryDequeue(out perfEvent))
                    {
                        if (!_running)
                        {
                            return;
                        }

                        spinWait.SpinOnce();
                    }

                    spinWait.Reset();

                    _eventHandler.OnBatchStart(1);
                    _eventHandler.OnEvent(perfEvent, perfEvent.Value, true);
                }
            });

            started.Wait();
        }
 public void Start()
 {
     _rwh       = ThreadPool.UnsafeRegisterWaitForSingleObject(_eh, OnWait, null, 100, false);
     _isRunning = true;
     _task      = Task.Run(async() => {
         var sw = new SpinWait();
         while (_isRunning)
         {
             var currentValue = _df.Buffer.VolatileReadInt64(0);
             if (currentValue > _lastSeenValue)
             {
                 // nore that on next iteration we will see only the last value
                 _action.Invoke(_lastSeenValue, currentValue);
                 _lastSeenValue = currentValue;
             }
             else
             {
                 if (!sw.NextSpinWillYield)
                 {
                     sw.SpinOnce();
                 }
                 else
                 {
                     sw.Reset();
                     await _sem.WaitAsync(100);
                 }
             }
         }
     });
 }
Esempio n. 7
0
        private void PerformCleanupImpl()
        {
            SpinWait wait = new SpinWait();

            while (true)
            {
                CleanupSourceState state  = this.State;
                CleanupSourceState state2 = (state | CleanupSourceState.Cleaning) & ~CleanupSourceState.CleanupNeeded;
                CleanupSourceState state3 = (CleanupSourceState)Interlocked.CompareExchange(ref this.state, (int)state2, (int)state);
                if (state == state3)
                {
                    break;
                }
                wait.SpinOnce();
            }
            this.OnPerformCleanup();
            wait.Reset();
            while (true)
            {
                CleanupSourceState state4 = this.State;
                CleanupSourceState state5 = state4 & ~CleanupSourceState.Cleaning;
                CleanupSourceState state6 = (CleanupSourceState)Interlocked.CompareExchange(ref this.state, (int)state5, (int)state4);
                if (state4 == state6)
                {
                    break;
                }
                wait.SpinOnce();
            }
        }
Esempio n. 8
0
        private void WriteToAppenders()
        {
            var spinWait     = new SpinWait();
            var stringBuffer = new StringBuffer(OutputBufferSize);
            var destination  = new byte[OutputBufferSize];
            var flush        = false;

            while (_isRunning || !_queue.IsEmpty)
            {
                if (TryToProcessQueue(stringBuffer, destination))
                {
                    spinWait.Reset();
                    flush = true;
                    continue;
                }

                if (flush && spinWait.NextSpinWillYield && Config.FlushAppenders)
                {
                    FlushAppenders();
                    flush = false;
                }
                else
                {
                    spinWait.SpinOnce();
                }
            }

            FlushAppenders();
        }
        void TryDoWork(int index)
        {
            _countEvt.Signal();
            Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId} started do work {index}");
            var spinWait = new SpinWait();

            while (!_isDisposed)
            {
                bool isDeququed = _workItems.TryDequeue(out var callback);
                if (isDeququed)
                {
                    callback(null);
                    continue;
                }

                _mre.Reset();

                if (spinWait.NextSpinWillYield)
                {
                    Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId} WAIT ONE");
                    _mre.WaitOne();
                    spinWait.Reset();
                }
                spinWait.SpinOnce();
            }
            Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId} finished do work {index}");
            _barrier.SignalAndWait();
        }
Esempio n. 10
0
        /// <summary>
        /// Adds the item to the AsyncCollection.
        /// </summary>
        /// <param name="item">The item to be added to the collection. The value can be a null reference.</param>
        /// <exception cref="T:System.InvalidOperationException">The AsyncCollection has been marked as complete with regards to additions.</exception>
        /// <exception cref="T:System.ObjectDisposedException">The AsyncCollection has been disposed.</exception>
        public void Add(T item)
        {
            CheckDisposed();

            SpinWait spinner = new SpinWait();

            while (true)
            {
                int observedAdders = currentAdders;
                if ((observedAdders & COMPLETE_ADDING_ON_MASK) != 0)
                {
                    spinner.Reset();
                    while (currentAdders != COMPLETE_ADDING_ON_MASK)
                    {
                        spinner.SpinOnce();
                    }
                    throw new InvalidOperationException("Adding is completed");
                }
                if (Interlocked.CompareExchange(ref currentAdders, observedAdders + 1, observedAdders) == observedAdders)
                {
                    break;
                }
                spinner.SpinOnce();
            }


            queue.Enqueue(item);
            semaphore.Release();

            Interlocked.Decrement(ref currentAdders);
        }
Esempio n. 11
0
        public void Operate(long busy)
        {
            _FPS.Update();

            if (_Busy <= busy && _FPS.Value > _LowPower)
            {
                _SpinWait.SpinOnce();
                _SpinCount++;
            }
            else
            {
                _SpinWait.Reset();
                _WorkCount++;
            }

            if (_TimeCount.Second > _Sample)
            {
                Power = _WorkCount / (_WorkCount + _SpinCount);

                _WorkCount = 0;
                _SpinCount = 0;
                _TimeCount.Reset();
            }

            _Busy = busy;
        }
Esempio n. 12
0
        public long Run(ThroughputSessionContext sessionContext)
        {
            _eventHandler.Reset(_iterations - 1);
            _consumer.Start();

            sessionContext.Start();

            var spinWait = new SpinWait();

            for (long i = 0; i < _iterations; i++)
            {
                var data = new PerfEvent {
                    Value = i
                };
                while (!_channel.Writer.TryWrite(data))
                {
                    spinWait.SpinOnce();
                }
                spinWait.Reset();
            }

            _eventHandler.Latch.WaitOne();
            sessionContext.Stop();
            _consumer.Stop();

            sessionContext.SetBatchData(_eventHandler.BatchesProcessedCount.Value, _iterations);

            PerfTestUtil.FailIfNot(_expectedResult, _eventHandler.Value, $"Handler should have processed {_expectedResult} events, but was: {_eventHandler.Value}");

            return(_iterations);
        }
Esempio n. 13
0
        protected virtual void _loop_thread_func(object obj)
        {
            // Use a spin wait loop to get higher timing accurancy
            SpinWait spin_wait = new SpinWait();

            long next_wait = _stopwatch.ElapsedMilliseconds;

            long now = next_wait;

            while (_keep_going)
            {
                _run_timestep(now);

                now = _stopwatch.ElapsedMilliseconds;

                do
                {
                    next_wait += _update_period;
                }while (next_wait <= now);

                spin_wait.Reset();
                while ((now = _stopwatch.ElapsedMilliseconds) < next_wait)
                {
                    spin_wait.SpinOnce();
                }
            }
        }
        private void StartSchedule()
        {
            Task.Run(() =>
            {
                SpinWait sw = new SpinWait();
                while (!this.cancellationTokenSource.Token.IsCancellationRequested &&
                       (!this.controllerQueue.IsCompleted || Interlocked.Read(ref this.activeControllerItemCount) != 0))
                {
                    this.FillInQueue(
                        this.activeControllerItems,
                        this.controllerQueue,
                        this.cancellationTokenSource.Token);

                    if (!this.cancellationTokenSource.Token.IsCancellationRequested)
                    {
                        // If we don't have the requested amount of active tasks
                        // running, get a task item from any active transfer item
                        // that has work available.
                        if (!this.DoWorkFrom(this.activeControllerItems))
                        {
                            sw.SpinOnce();
                        }
                        else
                        {
                            sw.Reset();
                            continue;
                        }
                    }
                }
            });
        }
        /// <summary>
        /// Marks the <see cref="T:System.Collections.Concurrent.BlockingCollection{T}"/> instances
        /// as not accepting any more additions.
        /// </summary>
        /// <remarks>
        /// After a collection has been marked as complete for adding, adding to the collection is not permitted
        /// and attempts to remove from the collection will not wait when the collection is empty.
        /// </remarks>
        /// <exception cref="T:System.ObjectDisposedException">The <see
        /// cref="T:System.Collections.Concurrent.BlockingCollection{T}"/> has been disposed.</exception>
        public void CompleteAdding()
        {
            CheckDisposed();

            if (IsAddingCompleted)
            {
                return;
            }

            SpinWait spinner = new SpinWait();

            while (true)
            {
                int observedAdders = m_currentAdders;
                if ((observedAdders & COMPLETE_ADDING_ON_MASK) != 0)
                {
                    spinner.Reset();
                    // If there is another COmpleteAdding in progress waiting the current adders, then spin until it finishes
                    while (m_currentAdders != COMPLETE_ADDING_ON_MASK)
                    {
                        spinner.SpinOnce();
                    }
                    return;
                }

                if (Interlocked.CompareExchange(ref m_currentAdders, observedAdders | COMPLETE_ADDING_ON_MASK, observedAdders) == observedAdders)
                {
                    spinner.Reset();
                    while (m_currentAdders != COMPLETE_ADDING_ON_MASK)
                    {
                        spinner.SpinOnce();
                    }

                    if (Count == 0)
                    {
                        CancelWaitingConsumers();
                    }

                    // We should always wake waiting producers, and have them throw exceptions as
                    // Add&CompleteAdding should not be used concurrently.
                    CancelWaitingProducers();
                    return;
                }
                spinner.SpinOnce();
            }
        }
Esempio n. 16
0
        public void TickLoop()
        {
            logger.Info("Network loop started.");
            Work work;

            while (true)
            {
                try
                {
                    if (Manager.Terminating)
                    {
                        break;
                    }
                    loopLock.Reset();
                    while (pendings.TryDequeue(out work))
                    {
                        try
                        {
                            if (Manager.Terminating)
                            {
                                return;
                            }
                            if (work.Item1.Stage == ProtocalStage.Disconnected)
                            {
                                Client client;
                                var    accId = work.Item1?.Account?.AccountId;
                                if (accId != null)
                                {
                                    Manager.Clients.TryRemove(accId, out client);
                                }
                                continue;
                            }
                            try
                            {
                                work.Item1.ProcessPacket(work.Item2);
                            }
                            catch (Exception ex)
                            {
                                logger.Error(ex);
                            }
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex);
                        }
                    }
                    while (pendings.Count == 0 && !Manager.Terminating)
                    {
                        loopLock.SpinOnce();
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                }
            }
            logger.Info("Network loop stopped.");
        }
Esempio n. 17
0
        public void TickLoop()
        {
            log.Info("Network loop started.");
            Work work;

            do
            {
                try
                {
                    if (Manager.Terminating)
                    {
                        break;
                    }

                    loopLock.Reset();

                    while (pendings.TryDequeue(out work))
                    {
                        try
                        {
                            if (Manager.Terminating)
                            {
                                return;
                            }

                            if (work.Item1.State == ProtocolState.Disconnected)
                            {
                                Client client;
                                Manager.Clients.TryRemove(work.Item1.Id.ToString(), out client);
                                continue;
                            }
                            try
                            {
                                work.Item1.ProcessMessage(work.Item2);
                            }
                            catch (Exception ex)
                            {
                                log.Error(ex);
                            }
                        }
                        catch (Exception ex)
                        {
                            log.Error(ex);
                        }
                    }
                    while (pendings.Count == 0 && !Manager.Terminating)
                    {
                        loopLock.SpinOnce();
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            } while (true);
            log.Info("Network loop stopped.");
        }
Esempio n. 18
0
        public void TickLoop()
        {
            if (CheckConfig.IsDebugOn())
            {
                Console.WriteLine("Procces: Starting network loop.");
            }
            Work work;

            while (true)
            {
                if (Manager.Terminating)
                {
                    break;
                }
                loopLock.Reset();
                while (pendings.TryDequeue(out work))
                {
                    if (Manager.Terminating)
                    {
                        return;
                    }
                    try
                    {
                        if (work.Item1.Stage == ProtocalStage.Disconnected)
                        {
                            Client client;
                            var    accId = work.Item1?.Account?.AccountId;
                            if (accId != null)
                            {
                                Manager.Clients.TryRemove(accId, out client);
                            }
                            continue;
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        throw;
                    }
                    try
                    {
                        Packet packet = Packet.Packets[work.Item2].CreateInstance();
                        packet.Read(work.Item1, work.Item3, 0, work.Item3.Length);
                        work.Item1.ProcessPacket(packet);
                    }
                    catch { }
                }
                while (pendings.Count == 0 && !Manager.Terminating)
                {
                    loopLock.SpinOnce();
                }
            }
            if (CheckConfig.IsDebugOn())
            {
                Console.WriteLine("Procces: Stopping network loop.");
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        private void InternalDispose()
        {
            if (Interlocked.CompareExchange(ref isClosed, 1, 0) == 0)
            {
                //closing = true;
                if (LOG.IsDebugEnabled)
                {
                    LOG.DebugFormat("Closing client for session: 0x{0:X}", SessionId);
                }

                try
                {
                    SubmitRequest(new RequestHeader {
                        Type = (int)OpCode.CloseSession
                    }, null, null, null);
                    SpinWait spin      = new SpinWait();
                    DateTime timeoutAt = DateTime.UtcNow.Add(SessionTimeout);
                    while (!producer.IsConnectionClosedByServer)
                    {
                        spin.SpinOnce();
                        if (spin.Count > MaximumSpin)
                        {
                            if (timeoutAt <= DateTime.UtcNow)
                            {
                                throw new TimeoutException(
                                          string.Format("Timed out in Dispose() while closing session: 0x{0:X}", SessionId));
                            }
                            spin.Reset();
                        }
                    }
                }
                catch (ThreadInterruptedException)
                {
                    // ignore, close the send/event threads
                }
                catch (Exception ex)
                {
                    LOG.WarnFormat("Error disposing {0} : {1}", this.GetType().FullName, ex.Message);
                }
                finally
                {
                    //fixed by Yang Li: 当从客户端传来的connectstring是个非法格式的ip地址时,producer和consumer都为null:

                    //producer.Dispose();
                    //consumer.Dispose();

                    if (producer != null)
                    {
                        producer.Dispose();
                    }
                    if (consumer != null)
                    {
                        consumer.Dispose();
                    }
                }
            }
        }
 private object ExchangeWithSentinel(object[] arr, int i, object sentinel, SpinWait spinWait)
 {
   spinWait.Reset();
   while(true) {
     var vi = Interlocked.Exchange(ref arr[i], sentinel);
     if(vi != sentinel) return vi;
     spinWait.SpinOnce();
   }
 }
Esempio n. 21
0
        private void StartDataExtrapolation(int desiredEventsCount)
        {
            desiredEventsCount -= _allEvents.Count;
            if (desiredEventsCount <= 0)
            {
                _extrapolationCompleted = true;
                return;
            }

            var thread = new Thread(() =>
            {
                var random               = new Random();
                var spinWait             = new SpinWait();
                int totalEventsGenerated = 0;
                long lastEventTime       = _allEvents[_allEvents.Count - 1].Ticks;

                Console.WriteLine("\nExtrapolation started...");

                while (totalEventsGenerated < desiredEventsCount)
                {
                    var baseIndex = random.Next(0, _allEvents.Count);
                    if (_allEvents[baseIndex].EventType == EventType.Stop)
                    {
                        baseIndex++;
                    }

                    if (baseIndex >= _allEvents.Count)
                    {
                        continue;
                    }

                    long diff = Math.Abs(_allEvents[baseIndex].Ticks - lastEventTime) + 100;

                    for (var i = baseIndex; i < _allEvents.Count; i++)
                    {
                        lastEventTime = diff + _allEvents[i].Ticks;
                        _queue.Enqueue(new RealEvent(_allEvents[i].EventType, lastEventTime));
                        totalEventsGenerated++;
                    }

                    _eventsBatchGenerated.Set();

                    while (_queue.Count > 1000)
                    {
                        spinWait.SpinOnce();
                    }

                    spinWait.Reset();
                }

                _extrapolationCompleted = true;
            });

            thread.Start();
        }
Esempio n. 22
0
        /// <summary>
        /// Marks the AsyncCollection instance as not accepting any more additions.
        /// </summary>
        /// <remarks>
        /// After a collection has been marked as complete for adding, adding to the collection is not permitted
        /// and attempts to remove from the collection will not wait when the collection is empty.
        /// </remarks>
        /// <exception cref="T:System.ObjectDisposedException">The AsyncCollection has been disposed.</exception>
        public void CompleteAdding()
        {
            CheckDisposed();

            if (IsAddingCompleted)
            {
                return;
            }

            SpinWait spinner = new SpinWait();

            while (true)
            {
                int observedAdders = currentAdders;
                if ((observedAdders & COMPLETE_ADDING_ON_MASK) != 0)
                {
                    spinner.Reset();
                    while (currentAdders != COMPLETE_ADDING_ON_MASK)
                    {
                        spinner.SpinOnce();
                    }
                    return;
                }

                if (Interlocked.CompareExchange(ref currentAdders, observedAdders | COMPLETE_ADDING_ON_MASK, observedAdders) == observedAdders)
                {
                    spinner.Reset();
                    while (currentAdders != COMPLETE_ADDING_ON_MASK)
                    {
                        spinner.SpinOnce();
                    }

                    if (queue.Count == 0)
                    {
                        doneCancellationToken.Cancel();
                    }

                    return;
                }
                spinner.SpinOnce();
            }
        }
Esempio n. 23
0
        protected void OnRunning()
        {
            SpinWait wait = new SpinWait();

            while (true)
            {
                int state = m_state;
                if (state == State.ScheduledToRun && Interlocked.CompareExchange(ref m_state, State.Running, State.ScheduledToRun) == State.ScheduledToRun)
                {
                    break;
                }
                if (state == State.ScheduledToRunAfterDelay && Interlocked.CompareExchange(ref m_state, State.Running, State.ScheduledToRunAfterDelay) == State.ScheduledToRunAfterDelay)
                {
                    break;
                }
                wait.SpinOnce();
            }
            wait.Reset();

            m_runAgain           = false;
            m_runAgainAfterDelay = -1;

            Thread.MemoryBarrier();

            m_args.StartDisposalCallSuccessful = m_startDisposalCallSuccessful;
            bool failedRun = !m_callback.TryInvoke(m_args);

            if (m_args.ShouldDispose || failedRun)
            {
                InternalDispose_FromWorkerThread();
                Interlocked.Exchange(ref m_state, State.Disposed);
                return;
            }

            Interlocked.Exchange(ref m_state, State.AfterRunning); //Notifies that the RunAgain and RunAgainAfterDelay variables are going to be used
            //                                                       to make decisions. Therefore, if setting these variables after this point, modifying the state machine will be
            //                                                       necessary

            if (m_runAgain)
            {
                Interlocked.Exchange(ref m_state, State.ScheduledToRun);
                InternalStart_FromWorkerThread();
            }
            else if (m_runAgainAfterDelay >= 0)
            {
                InternalStart_FromWorkerThread(m_runAgainAfterDelay);
                Interlocked.Exchange(ref m_state, State.ScheduledToRunAfterDelay);
            }
            else
            {
                InternalDoNothing_FromWorkerThread();
                Interlocked.Exchange(ref m_state, State.NotRunning);
            }
        }
Esempio n. 24
0
        private static void runTask(object obj)
        {
            if (obj is not TaskState state)
            {
                throw new InvalidOperationException($"Task {obj} is not a {typeof(TaskState)}");
            }

            try
            {
                Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;

                var spin            = new SpinWait();
                var sleep0Threshold = 10;
                var sleepCount      = 0;
                while (false == state.Token.IsCancellationRequested)
                {
                    Volatile.Write(ref state.ProcessorId, Thread.GetCurrentProcessorId());

                    var hasRanBatch = !state.Batches.IsEmpty;
                    while (state.Batches.TryTake(out var queued))
                    {
                        queued.Batch.Execute(queued.Index, queued.MaxUseIndex, state.TaskIndex, state.TaskCount);
                        if (Interlocked.Increment(ref state.Results[queued.BatchId].SuccessfulWrite) == state.Results[queued.BatchId].MaxIndex &&
                            queued.Batch is IBatchOnComplete onComplete)
                        {
                            onComplete.OnCompleted(null);
                        }
                    }

                    if (state.IsPerformanceCritical)
                    {
                        if (sleepCount++ > sleep0Threshold)
                        {
                            Thread.Sleep(0);
                            sleepCount = 0;
                        }

                        continue;
                    }

                    spin.SpinOnce(30);
                    if (hasRanBatch)
                    {
                        spin.Reset();
                        sleepCount = 0;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Esempio n. 25
0
 public void SpinOnce()
 {
     if (_spinWait.NextSpinWillYield)
     {
         Thread.Sleep(0);
         _spinWait.Reset();
     }
     else
     {
         _spinWait.SpinOnce();
     }
 }
Esempio n. 26
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        private void InternalDispose()
        {
            if (Interlocked.CompareExchange(ref isClosed, 1, 0) == 0)
            {
                //closing = true;
                if (LOG.IsDebugEnabled)
                {
                    LOG.DebugFormat("Closing client for session: 0x{0:X}", SessionId);
                }

                try
                {
                    ReplyHeader r = SubmitRequest(new RequestHeader {
                        Type = (int)OpCode.CloseSession
                    }, null, null, null);

                    // @@@ Fixed a shutdown deadlock bug
                    // @@@ Repro steps.
                    // @@@  1. Run ZooKeeper server
                    // @@@  2. Client (ZooKeeperNet) connect to the server and issue some commands
                    // @@@  3. Kill ZooKeeper server
                    // @@@  4. Close (exit) ZooKeeper client
                    // @@@
                    // @@@ Added error code checking in ReplayHeader to prevent the infinite spin waiting.
                    // @@@ TODO: It'd be a good idea add some waiting timeout inside the spin waiting loop.
                    if (r.Err == 0 /* (int)KeeperException.Code.OK */)
                    {
                        SpinWait spin = new SpinWait();
                        while (!producer.IsConnectionClosedByServer)
                        {
                            spin.SpinOnce();
                            if (spin.Count > maxSpin)
                            {
                                spin.Reset();
                            }
                        }
                    }
                }
                catch (ThreadInterruptedException)
                {
                    // ignore, close the send/event threads
                }
                catch (Exception ex)
                {
                    LOG.WarnFormat("Error disposing {0} : {1}", this.GetType().FullName, ex.Message);
                }
                finally
                {
                    producer.Dispose();
                    consumer.Dispose();
                }
            }
        }
        public void TickLoop()
        {
            log.Info("Network loop started.");
            while (true)
            {
                if (Manager.Terminating)
                {
                    break;
                }
                loopLock.Reset();

                //Do we really need this?
                //foreach (var i in Manager.Clients)
                //{
                //    if (i.Value.Stage == ProtocalStage.Disconnected)
                //    {
                //        Manager.Clients.TryRemove(i.Key, out client);
                //    }
                //}

                Work work;
                while (pendings.TryDequeue(out work))
                {
                    if (Manager.Terminating)
                    {
                        return;
                    }
                    if (work.Item1.Stage == ProtocalStage.Disconnected && work.Item1.Account != null)
                    {
                        Client client;
                        Manager.Clients.TryRemove(work.Item1.Account.AccountId, out client);
                        continue;
                    }
                    try
                    {
                        var packet = Packet.Packets[work.Item2].CreateInstance();
                        packet.Read(work.Item1, work.Item3, 0, work.Item3.Length);
                        work.Item1.ProcessPacket(packet);
                    }
                    catch (Exception ex)
                    {
                        log.Error("Error while reading or processing packet:\n", ex);
                    }
                }
                while (pendings.Count == 0 && !Manager.Terminating)
                {
                    loopLock.SpinOnce();
                }
            }
            log.Info("Network loop stopped.");
        }
Esempio n. 28
0
        public void CompleteAdding()
        {
            this.CheckDisposed();
            if (this.IsAddingCompleted)
            {
                return;
            }
            SpinWait spinWait = new SpinWait();

            while (true)
            {
                int mCurrentAdders = this.m_currentAdders;
                if ((mCurrentAdders & -2147483648) != 0)
                {
                    spinWait.Reset();
                    while (this.m_currentAdders != -2147483648)
                    {
                        spinWait.SpinOnce();
                    }
                    return;
                }
                if (Interlocked.CompareExchange(ref this.m_currentAdders, mCurrentAdders | -2147483648, mCurrentAdders) == mCurrentAdders)
                {
                    break;
                }
                spinWait.SpinOnce();
            }
            spinWait.Reset();
            while (this.m_currentAdders != -2147483648)
            {
                spinWait.SpinOnce();
            }
            if (this.Count == 0)
            {
                this.CancelWaitingConsumers();
            }
            this.CancelWaitingProducers();
        }
Esempio n. 29
0
        public void TickLoop()
        {
            log.Info("Network loop started.");
            Work   work;
            Client client;

            while (true)
            {
                if (Manager.Terminating)
                {
                    break;
                }
                loopLock.Reset();

                foreach (var i in Manager.Clients)
                {
                    if (i.Value.Stage == ProtocalStage.Disconnected)
                    {
                        Manager.Clients.TryRemove(i.Key, out client);
                    }
                }

                while (pendings.TryDequeue(out work))
                {
                    if (Manager.Terminating)
                    {
                        return;
                    }
                    if (work.Item1.Stage == ProtocalStage.Disconnected && work.Item1.Account != null)
                    {
                        Manager.Clients.TryRemove(work.Item1.Account.AccountId, out client);
                        continue;
                    }
                    try
                    {
                        Packet packet = Packet.Packets[work.Item2].CreateInstance();
                        packet.Read(work.Item1, work.Item3, 0, work.Item3.Length);
                        work.Item1.ProcessPacket(packet);
                    }
                    catch
                    {
                    }
                }
                while (pendings.Count == 0 && !Manager.Terminating)
                {
                    loopLock.SpinOnce();
                }
            }
            log.Info("Network loop stopped.");
        }
Esempio n. 30
0
        public void Dispatch(Action <TWorkItem, CancellationToken> action, CancellationToken cancellationToken)
        {
            using var locals = new WorkQueueLocals(this);
            try
            {
                CustomWorkQueueNonGenericStore.LocalQueue = locals.Queue;

                var waitAdded = false;
                var spinWait  = new SpinWait();

                while (!cancellationToken.IsCancellationRequested)
                {
                    if (TryDequeue(locals, out var work, out var missedSteal))
                    {
                        if (!waitAdded)
                        {
                            SignalOneThread();
                        }

                        do
                        {
                            action(work, cancellationToken);
                        } while (TryDequeue(locals, out work, out missedSteal));
                    }

                    if (!waitAdded)
                    {
                        AddWaitNode(locals.WaitNode, ref spinWait);
                        waitAdded = true;
                        continue;
                    }

                    if (missedSteal)
                    {
                        spinWait.SpinOnce();
                        continue;
                    }

                    locals.Semaphore.Wait(cancellationToken);
                    spinWait.Reset();
                    waitAdded = false;
                }

                cancellationToken.ThrowIfCancellationRequested();
            }
            finally
            {
                CustomWorkQueueNonGenericStore.LocalQueue = null;
            }
        }
        protected override void ConsumeItems( int count )
        {
            SpinWait spinWait = new SpinWait();
            int value;

            for ( int i = 0; i < count; )
            {
                if ( this.queue.TryDequeue( out value ) )
                {
                    i++;

                    spinWait.Reset();
                }
                else
                {
                    spinWait.SpinOnce();
                }
            }
        }
        private void StartSchedule()
        {
            Task.Run(() =>
                {
                    SpinWait sw = new SpinWait();
                    while (!this.cancellationTokenSource.Token.IsCancellationRequested &&
                        (!this.controllerQueue.IsCompleted || this.activeControllerItems.Any()))
                    {
                        FillInQueue(
                            this.activeControllerItems,
                            this.controllerQueue,
                            this.cancellationTokenSource.Token);

                        if (!this.cancellationTokenSource.Token.IsCancellationRequested)
                        {
                            // If we don't have the requested amount of active tasks
                            // running, get a task item from any active transfer item
                            // that has work available.
                            if (!this.DoWorkFrom(this.activeControllerItems))
                            {
                                sw.SpinOnce();
                            }
                            else
                            {
                                sw.Reset();
                                continue;
                            }
                        }
                    }
                });
        }