예제 #1
0
 public SequenceBarrier(ISequencer sequencer, IWaitStrategy waitStrategy, ISequence cursor, IEnumerable <ISequence> dependents)
 {
     this._sequencer    = sequencer;
     this._waitStrategy = waitStrategy;
     this._cursor       = cursor;
     this._dependent    = !dependents.Any() ? cursor : new SequenceGroup(dependents);
 }
 public ConcurrentRingBufferWriter(int bufferSize, IWaitStrategy waitStrategy)
     : base(waitStrategy)
 {
     _bufferSize = bufferSize;
     _nextFree   = new Sequence();
     _lastFree   = new Sequence(bufferSize - 1);
 }
 public Lite_Timeout_Blocking_Wait_Strategy_Test()
 {
     _barrier   = new DummySequenceBarrier();
     _strategy  = new LiteTimeoutBlockingWaitStrategy(TimeoutMilliseconds);
     _cursor    = new Sequence(5);
     _dependent = _cursor;
 }
예제 #4
0
 /// <summary>
 /// Create a new Disruptor.
 /// </summary>
 /// <param name="eventFactory">the factory to create events in the ring buffer.</param>
 /// <param name="claimStrategy">the claim strategy to use for the ring buffer.</param>
 /// <param name="waitStrategy">the wait strategy to use for the ring buffer.</param>
 /// <param name="taskScheduler">the <see cref="TaskScheduler"/> used to start <see cref="IEventProcessor"/>s.</param>
 public Disruptor(Func <T> eventFactory,
                  IClaimStrategy claimStrategy,
                  IWaitStrategy waitStrategy,
                  TaskScheduler taskScheduler)
     : this(new RingBuffer <T>(eventFactory, claimStrategy, waitStrategy), taskScheduler)
 {
 }
예제 #5
0
            //private          TWrite            _buffer;

            #endregion

            public SharedWriter(IWaitStrategy waitHandleReader, IWaitOnceStrategy waitHandleWriter, Synchronizer syncRoot, Action <TWrite> write)
            {
                _waitHandleReader = waitHandleReader;
                _waitHandleWriter = waitHandleWriter;
                _syncRoot         = syncRoot;
                _write            = write;
            }
 public TimeoutBlockingWaitStrategyTest()
 {
     _barrier   = new DummySequenceBarrier();
     _strategy  = new TimeoutBlockingWaitStrategy(TimeoutMilliseconds);
     _cursor    = new Sequence(5);
     _dependent = _cursor;
 }
        public MultiProducerSequencerRef2(int bufferSize, IWaitStrategy waitStrategy)
        {
            if (bufferSize < 1)
            {
                throw new ArgumentException("bufferSize must not be less than 1");
            }
            if (!bufferSize.IsPowerOf2())
            {
                throw new ArgumentException("bufferSize must be a power of 2");
            }

            _bufferSize             = bufferSize;
            _waitStrategy           = waitStrategy;
            _isBlockingWaitStrategy = !(waitStrategy is INonBlockingWaitStrategy);
#if NETCOREAPP
            _availableBuffer        = GC.AllocateArray <int>(bufferSize, pinned: true);
            _availableBufferPointer = (int *)Unsafe.AsPointer(ref _availableBuffer[0]);
#else
            _availableBuffer = new int[bufferSize];
#endif
            _indexMask  = bufferSize - 1;
            _indexShift = DisruptorUtil.Log2(bufferSize);

            InitialiseAvailableBuffer();
        }
 public ConcurrentRingBufferWriter(int bufferSize, IWaitStrategy waitStrategy)
     : base(waitStrategy)
 {
     _bufferSize = bufferSize;
     _nextFree = new Sequence();
     _lastFree = new Sequence(bufferSize - 1);
 }
예제 #9
0
 public SharedReader(IWaitStrategy waitHandleReader, IWaitOnceStrategy waitHandleWriter, Synchronizer syncRoot, Func <TRead> reader)
 {
     _waitHandleReader = waitHandleReader;
     _waitHandleWriter = waitHandleWriter;
     _reader           = reader;
     _syncRoot         = syncRoot;
 }
        //protected volatile Sequence[] gatingSequences = new Sequence[0];

        /// <summary>
        /// Create with the specified buffer size and wait strategy.
        /// </summary>
        /// <param name="bufferSize">The total number of entries, must be a positive power of 2.</param>
        /// <param name="waitStrategy">waitStrategy</param>
        public AbstractSequencer(int bufferSize, IWaitStrategy waitStrategy)
        {
            Verify(bufferSize);
            //this.sequencesRef = new _Volatile.AtomicReference<Sequence[]>(gatingSequences);
            this.bufferSize   = bufferSize;
            this.waitStrategy = waitStrategy;
        }
예제 #11
0
 public CustomSequenceBarrier(ISequencer sequencer, IWaitStrategy waitStrategy, Sequence cursorSequence, ISequence[] dependentSequences)
 {
     _sequencer               = sequencer;
     _waitStrategy            = waitStrategy;
     _dependentSequences      = new DependentSequenceGroup(cursorSequence, dependentSequences);
     _cancellationTokenSource = new CancellationTokenSource();
 }
예제 #12
0
 public MultiProducerSequencer(int bufferSize, IWaitStrategy waitStrategy)
     : base(bufferSize, waitStrategy)
 {
     _availableBuffer = new int[bufferSize];
     _indexMask       = bufferSize - 1;
     _indexShift      = Util.Log2(bufferSize);
     InitialiseAvailableBuffer();
 }
 public MultiProducerSequencer(int bufferSize, IWaitStrategy waitStrategy)
     : base(bufferSize, waitStrategy)
 {
     _availableBuffer = new int[bufferSize];
     _indexMask = bufferSize - 1;
     _indexShift = Util.Log2(bufferSize);
     InitialiseAvailableBuffer();
 }
예제 #14
0
 public ConsumerBarrier(RingBuffer <TU> ringBuffer, params IBatchConsumer[] consumers)
 {
     _ringBuffer   = ringBuffer;
     _consumers    = consumers;
     _waitStrategy = _ringBuffer._waitStrategy;
     _ringModMask  = _ringBuffer._ringModMask;
     _entries      = _ringBuffer._entries;
 }
 public ProcessingSequenceBarrier(IWaitStrategy waitStrategy, 
                        Sequence cursorSequence, 
                        Sequence[] dependentSequences)
 {
     _waitStrategy = waitStrategy;
     _cursorSequence = cursorSequence;
     _dependentSequences = dependentSequences;
 }
예제 #16
0
 public ProcessingSequenceBarrier(IWaitStrategy waitStrategy,
                                  Sequence cursorSequence,
                                  Sequence[] dependentSequences)
 {
     _waitStrategy       = waitStrategy;
     _cursorSequence     = cursorSequence;
     _dependentSequences = dependentSequences;
 }
예제 #17
0
        public void Initialize(int bufferSize, IWaitStrategy waitStrategy)
        {
            _availableBuffer = new int[bufferSize];
            _indexMask       = bufferSize - 1;
            _indexShift      = bufferSize.Log2();

            InitialiseAvailableBuffer();
        }
    private static void ShouldHandleLotsOfThreads <T>(IWaitStrategy waitStrategy, int iterations) where T : IHandler, new()
    {
        var disruptor  = new Disruptor <TestEvent>(TestEvent.Factory, 65_536, TaskScheduler.Current, ProducerType.Multi, waitStrategy);
        var ringBuffer = disruptor.RingBuffer;

        disruptor.SetDefaultExceptionHandler(new FatalExceptionHandler <TestEvent>());

        var publisherCount = Math.Max(1, Environment.ProcessorCount / 2);
        var handlerCount   = Math.Max(1, Environment.ProcessorCount / 2);

        var end   = new CountdownEvent(publisherCount);
        var start = new CountdownEvent(publisherCount);

        var handlers = new T[handlerCount];

        for (var i = 0; i < handlers.Length; i++)
        {
            var handler = new T();
            handler.Register(disruptor);
            handlers[i] = handler;
        }

        var publishers = new Publisher[publisherCount];

        for (var i = 0; i < publishers.Length; i++)
        {
            publishers[i] = new Publisher(ringBuffer, iterations, start, end);
        }

        disruptor.Start();

        foreach (var publisher in publishers)
        {
            Task.Run(publisher.Run);
        }

        end.Wait();

        var spinWait = new SpinWait();

        while (ringBuffer.Cursor < (iterations - 1))
        {
            spinWait.SpinOnce();
        }

        disruptor.Shutdown();

        foreach (var publisher in publishers)
        {
            Assert.That(publisher.Failed, Is.EqualTo(false));
        }

        foreach (var handler in handlers)
        {
            Assert.That(handler.MessagesSeen, Is.Not.EqualTo(0));
            Assert.That(handler.FailureCount, Is.EqualTo(0));
        }
    }
예제 #19
0
        /// <summary>
        /// Create a new multiple producer RingBuffer with the specified wait strategy.
        /// </summary>
        /// <param name="factory">used to create the events within the ring buffer.</param>
        /// <param name="bufferSize">number of elements to create within the ring buffer.</param>
        /// <param name="waitStrategy">used to determine how to wait for new elements to become available.</param>
        /// <returns>a constructed ring buffer.</returns>
        /// <exception cref="ArgumentException">if bufferSize is less than 1 or not a power of 2</exception>
        public static RingBuffer <TEvent> CreateMultiProducer(
            Func <TEvent> factory,
            int bufferSize,
            IWaitStrategy waitStrategy)
        {
            var sequencer = new MultiProducerSequencer(bufferSize, waitStrategy);

            return(new RingBuffer <TEvent>(sequencer, factory));
        }
예제 #20
0
 private static void ConfigureWaitStrategy(IWaitStrategy waitStrategy, UnmanagedDisruptor <SendRequestEntry> disruptor, SendCompletionProcessor sendCompletionProcessor)
 {
     switch (waitStrategy)
     {
     case HybridWaitStrategy hybridWaitStrategy:
         hybridWaitStrategy.SequenceBarrierForSendCompletionProcessor = disruptor.GetBarrierFor(sendCompletionProcessor);
         return;
     }
 }
 public PhasedBackoffWaitStrategy(
     TimeSpan spinTimeout,
     TimeSpan yieldTimeout,
     IWaitStrategy fallbackStrategy)
 {
     _spinTimeoutTicks  = spinTimeout.Ticks;
     _yieldTimeoutTicks = spinTimeout.Ticks + yieldTimeout.Ticks;
     _fallbackStrategy  = fallbackStrategy;
 }
예제 #22
0
        /// <summary>
        /// Create a new single producer RingBuffer with the specified wait strategy.
        /// </summary>
        /// <param name="factory"></param>
        /// <param name="bufferSize"></param>
        /// <param name="waitStrategy"></param>
        /// <returns></returns>
        public static RingBuffer <TEvent> CreateSingleProducer(
            IEventFactory <TEvent> factory,
            int bufferSize,
            IWaitStrategy waitStrategy)
        {
            var sequencer = new SingleProducerSequencer(bufferSize, waitStrategy);

            return(new RingBuffer <TEvent>(sequencer, factory));
        }
        /// <summary>
        /// Create a new <see cref="ProcessingSequenceBarrier{TSequencer,TWaitStrategy}"/> with dedicated generic arguments.
        /// </summary>
        public static ISequenceBarrier Create(ISequencer sequencer, IWaitStrategy waitStrategy, Sequence cursorSequence, ISequence[] dependentSequences)
        {
            var sequencerProxy    = StructProxy.CreateProxyInstance(sequencer);
            var waitStrategyProxy = StructProxy.CreateProxyInstance(waitStrategy);

            var sequencerBarrierType = typeof(ProcessingSequenceBarrier <,>).MakeGenericType(sequencerProxy.GetType(), waitStrategyProxy.GetType());

            return((ISequenceBarrier)Activator.CreateInstance(sequencerBarrierType, sequencerProxy, waitStrategyProxy, cursorSequence, dependentSequences));
        }
 /// <summary>
 ///  Create a new Disruptor.
 /// </summary>
 /// <param name="eventFactory">the factory to Create events in the ring buffer.</param>
 /// <param name="ringBufferSize">ringBufferSize</param>
 /// <param name="taskScheduler">an <see cref="TaskScheduler"/> to execute event processors.</param>
 /// <param name="producerType">the claim strategy to use for the ring buffer.</param>
 /// <param name="waitStrategy">the wait strategy to use for the ring buffer.</param>
 public Disruptor(Func <T> eventFactory,
                  int ringBufferSize,
                  TaskScheduler taskScheduler,
                  ProducerType producerType,
                  IWaitStrategy waitStrategy)
     : this(RingBuffer <T> .Create(producerType, eventFactory, ringBufferSize, waitStrategy),
            taskScheduler)
 {
 }
 public MultiProducerSequencer(int bufferSize, IWaitStrategy waitStrategy)
     : base(bufferSize, waitStrategy)
 {
     indexMask = bufferSize - 1;
     indexShift = Util.Log2(bufferSize);
     pendingPublication = new _Volatile.IntegerArray(bufferSize);
     _pendingMask = bufferSize - 1;
     InitialiseAvailableBuffer();
 }
예제 #26
0
파일: WorkerTest.cs 프로젝트: GaelOn/Stream
 public WorkerTest(IMessageVisitorFactory msgVisitorFactory, IWaitStrategy wait, Func <TIn, TOut> funWork, Queue <IMessage> readQueue, Action <IMessage> push)
 {
     _queue         = readQueue;
     _funWork       = funWork;
     _push          = push;
     _wait          = wait;
     _msgVisitor    = msgVisitorFactory.Create(this);
     OnEndOfStream += OnEndOfStreamHandler;
 }
 public MultiProducerSequencer(int bufferSize, IWaitStrategy waitStrategy)
     : base(bufferSize, waitStrategy)
 {
     indexMask          = bufferSize - 1;
     indexShift         = Util.Log2(bufferSize);
     pendingPublication = new _Volatile.IntegerArray(bufferSize);
     _pendingMask       = bufferSize - 1;
     InitialiseAvailableBuffer();
 }
        public static void AssertWaitForWithDelayOf(long sleepTimeMillis, IWaitStrategy waitStrategy)
        {
            var sequenceUpdater = new SequenceUpdater(sleepTimeMillis, waitStrategy);
            Task.Factory.StartNew(sequenceUpdater.Run);
            sequenceUpdater.WaitForStartup();
            var cursor = new Sequence(0);
            var sequence = waitStrategy.WaitFor(0, cursor, sequenceUpdater.Sequence, new DummySequenceBarrier());

            Assert.That(sequence, Is.EqualTo(0L));
        }
예제 #29
0
        public TaskWorkerTest(Func <TIn, TOut> funWork, Queue <IMessage> qin, IWaitStrategy wait = null, CancellationToken ct = default)
        {
            _qout = new ConcurrentQueue <IMessage>();
            var _wait = wait ?? new SleepStrategy();
            var workerVisitorFactory = new MessageVisitorFactory();
            var worker = new WorkerTest <TIn, TOut>(workerVisitorFactory, _wait, funWork, qin, _qout.Enqueue);

            ct    = ct == null ? CancellationToken.None : ct;
            _task = Task.Factory.StartNew(() => worker.Start(), ct);
        }
        public static void AssertWaitForWithDelayOf(TimeSpan sleepTimeMillis, IWaitStrategy waitStrategy)
        {
            var sequenceUpdater = new SequenceUpdater(sleepTimeMillis, waitStrategy);
            Task.Factory.StartNew(() => sequenceUpdater.run(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
            sequenceUpdater.WaitForStartup();
            var cursor = new Sequence(0);
            var sequence = waitStrategy.WaitFor(0, cursor, sequenceUpdater.sequence, new DummySequenceBarrier());
            Assert.AreEqual(sequence, 0L);

        }
예제 #31
0
        /// <summary>
        /// Uses a busy spin strategy when waiting for a sequence to become available.
        /// </summary>
        public RingBufferBuilder <TEvent> UseSpinWaitStrategy()
        {
            if (_waitStrategy != null)
            {
                throw new InvalidOperationException("Wait strategy has already been set.");
            }

            _waitStrategy = new BusySpinWaitStrategy();
            return(this);
        }
        public static void assertWaitForWithDelayOf(int sleepTimeMillis, IWaitStrategy waitStrategy)
        {
            var sequenceUpdater = new SequenceUpdater(sleepTimeMillis, waitStrategy);

            Task.Factory.StartNew(() => sequenceUpdater.run(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
            sequenceUpdater.WaitForStartup();
            var cursor   = new Sequence(0);
            var sequence = waitStrategy.WaitFor(0, cursor, sequenceUpdater.sequence, new DummySequenceBarrier());

            //Assert.AreEqual(sequence, 0L);
        }
예제 #33
0
        public ProcessingSequenceBarrier(Sequencer sequencer,
                                         IWaitStrategy waitStrategy,
                                         Sequence cursorSequence,
                                         ISequence[] dependentSequences)
        {
            _waitStrategy   = waitStrategy;
            _cursorSequence = cursorSequence;
            _sequencer      = sequencer;

            _dependentSequence = 0 == dependentSequences.Length ? (ISequence)cursorSequence : new FixedSequenceGroup(dependentSequences);
        }
        public ProcessingSequenceBarrier(Sequencer sequencer, 
                                         IWaitStrategy waitStrategy, 
                                         Sequence cursorSequence, 
                                         ISequence[] dependentSequences)
        {
            _waitStrategy = waitStrategy;
            _cursorSequence = cursorSequence;
            _sequencer = sequencer;

            _dependentSequence = 0 == dependentSequences.Length ? (ISequence)cursorSequence : new FixedSequenceGroup(dependentSequences);
        }
예제 #35
0
        public static void AssertWaitForWithDelayOf(int sleepTimeMillis, IWaitStrategy waitStrategy)
        {
            var sequenceUpdater = new SequenceUpdater(sleepTimeMillis, waitStrategy);

            Task.Run(() => sequenceUpdater.Run());
            sequenceUpdater.WaitForStartup();
            var cursor   = new Sequence(0);
            var sequence = waitStrategy.WaitFor(0, cursor, sequenceUpdater.sequence, new DummySequenceBarrier());

            Assert.Equal(0L, sequence);
        }
예제 #36
0
 /// <summary>
 /// Create a new Disruptor.
 /// </summary>
 /// <param name="eventFactory">the factory to create events in the ring buffer.</param>
 /// <param name="ringBufferSize">the size of the ring buffer.</param>
 /// <param name="taskScheduler">a <see cref="TaskScheduler"/> to create threads for processors.</param>
 /// <param name="producerType">the claim strategy to use for the ring buffer.</param>
 /// <param name="waitStrategy">the wait strategy to use for the ring buffer.</param>
 public Disruptor(
     IEventFactory <T> eventFactory,
     int ringBufferSize,
     TaskScheduler taskScheduler,
     ProducerType producerType,
     IWaitStrategy waitStrategy)
     : this(
         RingBuffer <T> .Create(producerType, eventFactory, ringBufferSize, waitStrategy),
         new BasicExecutor(taskScheduler))
 {
 }
예제 #37
0
        public static void AssertWaitForWithDelayOf(long sleepTimeMillis, IWaitStrategy waitStrategy)
        {
            var sequenceUpdater = new SequenceUpdater(sleepTimeMillis, waitStrategy);

            Task.Factory.StartNew(sequenceUpdater.Run);
            sequenceUpdater.WaitForStartup();
            var cursor   = new Sequence(0);
            var sequence = waitStrategy.WaitFor(0, cursor, sequenceUpdater.Sequence, new DummySequenceBarrier());

            Assert.That(sequence, Is.EqualTo(0L));
        }
 public ProcessingSequenceBarrier(
                              ISequencer sequencer,
                              IWaitStrategy waitStrategy,
                              Sequence cursorSequence,
                              Sequence[] dependentSequences)
 {
     this.sequencer = sequencer;
     this.waitStrategy = waitStrategy;
     this.cursorSequence = cursorSequence;
     if (dependentSequences.Length == 0)
         this.dependentSequence = cursorSequence;
     else
         this.dependentSequence = new FixedSequenceGroup(dependentSequences);
 }
        public OneWriterManyReadersOneReader(uint bufferPower, int maxSequenceValue, bool delay)
        {
            _maxSequenceValue = maxSequenceValue;
            _delay = delay;

            _buffer = new RingBuffer<int>(bufferPower);

            _waitStrategy = new BlockingWaitStrategy();

            // init
            _committer = new RingBufferWriter(_buffer.Size, _waitStrategy);
            _journaler = new RingBufferReader(_waitStrategy);
            _replicator = new RingBufferReader(_waitStrategy);
            _processor = new RingBufferReader(_waitStrategy);

            // setup
            _committer.DependsOn(_processor);
            _journaler.DependsOn(_committer);
            _replicator.DependsOn(_committer);
            _processor.DependsOn(_journaler, _replicator);
        }
 public SequenceUpdater(TimeSpan sleepTime, IWaitStrategy waitStrategy)
 {
     this.sleepTime = sleepTime;
     this.waitStrategy = waitStrategy;
 }
 public SingleProducerSequencer(int bufferSize, IWaitStrategy waitStrategy)
     : base(bufferSize, waitStrategy)
 {
 }
예제 #42
0
 public RingBufferBarrier(IWaitStrategy waitStrategy)
 {
     Cursor = new Sequence();
     WaitStrategy = waitStrategy;
     _dependencies = EmptyDependencies;
 }
예제 #43
0
 private Sequencer NewProducer(ProducerType producerType, int bufferSize, IWaitStrategy waitStrategy)
 {
     switch (producerType)
     {
         case ProducerType.Single:
             return new SingleProducerSequencer(bufferSize, waitStrategy);
         case ProducerType.Multi:
             return new MultiProducerSequencer(bufferSize, waitStrategy);
         default:
             throw new ArgumentOutOfRangeException(nameof(producerType), producerType, null);
     }
 }
 private ISequencer newProducer(ProducerType producerType, int bufferSize, IWaitStrategy waitStrategy)
 {
     switch (producerType)
     {
         case ProducerType.SINGLE:
             return new SingleProducerSequencer(bufferSize, waitStrategy);
         case ProducerType.MULTI:
             return new MultiProducerSequencer(bufferSize, waitStrategy);
         default:
             throw new ArgumentException(producerType.ToString());
     }
 }
예제 #45
0
 public SequenceUpdater(long sleepTime, IWaitStrategy waitStrategy)
 {
     _sleepTime = (int)sleepTime;
     _waitStrategy = waitStrategy;
 }
예제 #46
0
 /// <summary>
 /// Construct a Sequencer with the selected strategies.
 /// </summary>
 /// <param name="claimStrategy">claimStrategy for those claiming sequences.</param>
 /// <param name="waitStrategy">waitStrategy for those waiting on sequences.</param>
 public Sequencer(IClaimStrategy claimStrategy, IWaitStrategy waitStrategy)
 {
     _claimStrategy = claimStrategy;
     _waitStrategy = waitStrategy;
 }
 public PhasedBackoffWaitStrategy(TimeSpan spinTimeout, TimeSpan yieldTimeout, IWaitStrategy fallbackStrategy)
 {
     _spinTimeoutTicks = spinTimeout.Ticks;
     _yieldTimeoutTicks = yieldTimeout.Ticks;
     _fallbackStrategy = fallbackStrategy;
 }
예제 #48
0
 public RingBufferReader(IWaitStrategy waitStrategy)
     : base(waitStrategy)
 {
 }