Exemple #1
0
        public unsafe void Test()
        {
            var       counter = Substitute.For <IStructSizeCounter>();
            const int aSize   = 64;

            counter.GetSize(typeof(A)).Returns(aSize);
            const int envelopeSize = 4;

            counter.GetSize(typeof(Envelope)).Returns(envelopeSize);

            var buffer = Substitute.For <IRingBuffer>();

            buffer.Write(0, new ByteChunk()).ReturnsForAnyArgs(true);
            const int messageId = 5;

            var asm = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("AnythingForTests"),
                                                                    AssemblyBuilderAccess.Run);
            var main   = asm.DefineDynamicModule("main");
            var writer = MessageWriterBuilder.Build(counter, l => messageId, new[] { typeof(A) }, main);

            var e = new Envelope(new ActorId(1));
            var a = new A();

            Assert.True(writer.Write(ref e, ref a, buffer));

            var call = buffer.ReceivedCalls().Single();
            var args = call.GetArguments();

            Assert.AreEqual("Write", call.GetMethodInfo().Name);
            Assert.AreEqual(messageId, args[0]);
            Assert.AreEqual(new ByteChunk((byte *)&a, aSize), args[1]);
        }
Exemple #2
0
        public unsafe void Actors()
        {
            using (var buffer =
                       new ManyToOneRingBuffer(new UnsafeBuffer(1024.Megabytes() + RingBufferDescriptor.TrailerLength)))
            {
                var someBytes = stackalloc byte[1];
                buffer.Write(5, new ByteChunk(someBytes, 1));
                buffer.Read((a, b) => { }, 1);

                var module = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("ActorsTestsDynAssembly"),
                                                                           AssemblyBuilderAccess.Run).DefineDynamicModule("main");
                var counter  = new StructSizeCounter();
                var registry =
                    new ActorRegistry(new[]
                                      { Tuple.Create(new ActorDescriptor(new Handler()), (IRingBuffer)buffer, new ActorId(1)) });
                var writer = MessageWriterBuilder.Build(counter, registry.GetMessageTypeId, new[] { typeof(A) }, module);

                var bus = new Bus(new ActorId(2), registry, 20, writer);

                var msg = new A();
                bus.Publish(ref msg);

                // publication is prepared do it

                var howMany    = 200000000;
                var oneMiliion = 1000000;

                using (var scheduler = new RoundRobinThreadAffinedTaskScheduler(4))
                {
                    var wait = new ManualResetEventSlim();
                    var t    = new CancellationToken();

                    var p1                = CreateProducer(wait, t, howMany, bus, scheduler);
                    var p2                = CreateProducer(wait, t, howMany, bus, scheduler);
                    var producentCount    = 2;
                    var totalMessageCount = howMany * producentCount;

                    var worker   = new Worker(totalMessageCount, wait, buffer, t);
                    var consumer = Task.Factory.StartNew(worker.DoWhile, t, TaskCreationOptions.LongRunning, scheduler);

                    GC.Collect(2, GCCollectionMode.Forced);

                    var sw = Stopwatch.StartNew();
                    wait.Set();

                    Task.WaitAll(p1, p2, consumer);

                    sw.Stop();
                    Console.WriteLine(
                        $"{howMany} messages written by each of {producentCount} producers and consumed in {sw.Elapsed}");
                    Console.WriteLine(
                        $"One million in {TimeSpan.FromMilliseconds(sw.Elapsed.TotalMilliseconds*oneMiliion/totalMessageCount)}");
                }
            }
        }
Exemple #3
0
        public unsafe void Setup()
        {
            _buffer = new ManyToOneRingBuffer(new UnsafeBuffer(1024.Megabytes() + RingBufferDescriptor.TrailerLength));
            var someBytes = stackalloc byte[1];

            _buffer.Write(5, new ByteChunk(someBytes, 1));
            _buffer.Read((a, b) => { }, 1);

            var module = AppDomain.CurrentDomain.DefineDynamicAssembly(
                new AssemblyName("ActorsTestsDynAssembly"),
                AssemblyBuilderAccess.Run).DefineDynamicModule("main");
            var counter  = new StructSizeCounter();
            var registry =
                new ActorRegistry(
                    new[]
                    { Tuple.Create(new ActorDescriptor(new Handler()), (IRingBuffer)_buffer, new ActorId(1)) });
            var writer = MessageWriterBuilder.Build(counter, registry.GetMessageTypeId, new[] { typeof(A) }, module);

            _bus = new Bus(new ActorId(2), registry, 20, writer);
        }
Exemple #4
0
        public Context Start(Action <Exception> exceptionAction = null)
        {
            var module = AppDomain.CurrentDomain.DefineDynamicAssembly(
                new AssemblyName("RampUp_MessageWriter_" + Guid.NewGuid()),
                AssemblyBuilderAccess.Run).DefineDynamicModule("main");

            InitMessageTypesDictionary();
            var writer = MessageWriterBuilder.Build(_counter, GetMessageId, _messageTypes.ToArray(), module);

            var runners = _registrations.Select(f => f()).ToList();

            if (_featureActors.Count > 0)
            {
                runners.Add(BuildRunner(_featureActors, new Bus()));
            }

            var registry = CreateRegistry(runners);

            foreach (var kvp in _runnerBusMap)
            {
                var index = runners.FindIndex(r => ReferenceEquals(r, kvp.Key));
                kvp.Value.Init(GetId(index), registry, ThrowAfterNTrials, writer);
            }

            var source = new CancellationTokenSource();
            var end    = new ManualResetEventSlim();
            var ctx    = new Context(source, end, new Bus(new ActorId(0), registry, ThrowAfterNTrials, writer));
            var token  = source.Token;

            _scheduler = new RoundRobinThreadAffinedTaskScheduler(runners.Count);
            var factory = new TaskFactory(_scheduler);

            var runningTasks = runners.Select(runner =>
            {
                return(factory.StartNew(() =>
                {
                    try
                    {
                        while (token.IsCancellationRequested == false)
                        {
                            BatchInfo info;
                            runner.SpinOnce(out info);
                        }
                    }
                    catch (TaskCanceledException)
                    {
                    }
                    catch (Exception)
                    {
                        source.Cancel();
                        throw;
                    }
                }, token));
            }).ToArray();

            // ReSharper disable once MethodSupportsCancellation
            Task.WhenAll(runningTasks).ContinueWith(t =>
            {
                _scheduler.Dispose();
                foreach (var buffer in _buffers)
                {
                    buffer.Dispose();
                }
                ctx.Exception = t.Exception;
                if (t.Exception != null)
                {
                    exceptionAction?.Invoke(t.Exception);
                }
                end.Set();
            });

            return(ctx);
        }