Esempio n. 1
0
        public static void SetAnonymousActorFiberFactory(FiberFactory fiberFactory)
        {
            Guard.AgainstNull(fiberFactory, "fiberFactory");
            _fiberFactory = fiberFactory;

            CreateAnonymousActorFactory();
        }
Esempio n. 2
0
        public List <IDisposable> CreateFileSystemEventProducers(string directory, bool usePolling, bool useFileSystemWatcher, UntypedChannel eventChannel, TimeSpan pollingInterval)
        {
            if (string.IsNullOrEmpty(directory))
            {
                throw new ArgumentException("Directory must not be null or empty.", "directory");
            }

            if (eventChannel != null)
            {
                throw new ArgumentException("A channel must be provided.", "eventChannel");
            }

            List <IDisposable> producers = new List <IDisposable>();

            FiberFactory fiberFactory = () => new SynchronousFiber();

            if (usePolling)
            {
                Scheduler   scheduler = new TimerScheduler(fiberFactory());
                IDisposable poller    = new PollingFileSystemEventProducer(directory, eventChannel,
                                                                           scheduler, fiberFactory(), pollingInterval);
                producers.Add(poller);
            }

            if (useFileSystemWatcher)
            {
                IDisposable watcher = new FileSystemEventProducer(directory, eventChannel);
            }

            return(producers);
        }
        public void A_file_is_created()
        {
            _baseDirectory = AppDomain.CurrentDomain.BaseDirectory;

            _filename = "test2.dat";
            _path     = Path.Combine(_baseDirectory, _filename);

            System.IO.File.Delete(_path);

            _listener = new Future <FileCreated>();

            _channel = new ChannelAdapter();
            FiberFactory fiberFactory = () => new SynchronousFiber();

            _scheduler = new TimerScheduler(fiberFactory());
            _producer  = new PollingFileSystemEventProducer(_baseDirectory, _channel, _scheduler, fiberFactory(),
                                                            20.Seconds());

            Thread.Sleep(5.Seconds());

            using (_channel.Connect(x => x.AddConsumerOf <FileCreated>().UsingConsumer(m => _listener.Complete(m))))
            {
                System.IO.File.Create(_path);

                _listener.WaitUntilCompleted(25.Seconds());
            }

            _producer.Dispose();
        }
Esempio n. 4
0
        bool RunTest <T>(int channelCount, int seedCount, Future <int> complete, Func <T> valueProvider)
        {
            var channels = new Channel <T> [channelCount];

            var latch = new CountdownLatch(channelCount * seedCount, complete.Complete);

            FiberFactory fiberFactory = () => new PoolFiber();

            for (int i = 0; i < channelCount; i++)
            {
                int channelNumber = i;
                channels[i] = new ConsumerChannel <T>(fiberFactory(), x =>
                {
                    if (channelNumber < channels.Length - 1)
                    {
                        channels[channelNumber + 1].Send(x);
                    }

                    latch.CountDown();
                });
            }

            for (int i = 0; i < seedCount; i++)
            {
                channels[i].Send(valueProvider());

                for (int j = 0; j < i; j++)
                {
                    latch.CountDown();
                }
            }

            return(complete.WaitUntilCompleted(24.Seconds()));
        }
Esempio n. 5
0
        public void SharedFiber_shutdown_should_not_disrupt_original_Fiber()
        {
            var atomicCounter = new AtomicCounter(0);
            var originalFiber = FiberFactory.CreateFiber(2); //going to use a dedicated thread Fiber
            var sharedFiber1  = new SharedFiber(originalFiber);
            var sharedFiber2  = sharedFiber1.Clone();

            for (var i = 0; i < 1000; i++)
            {
                originalFiber.Add(() => atomicCounter.GetAndIncrement());
                sharedFiber1.Add(() => atomicCounter.GetAndIncrement());
            }
            sharedFiber1.GracefulShutdown(TimeSpan.FromSeconds(1)).Wait(); //wait for the fiber to finish

            Assert.AreEqual(2000, atomicCounter.Current);                  //should have a total count of 2000

            for (var i = 0; i < 1000; i++)
            {
                originalFiber.Add(() => atomicCounter.GetAndIncrement());
                sharedFiber1.Add(() => atomicCounter.GetAndIncrement());
            }
            Thread.Sleep(TimeSpan.FromSeconds(1));
            Assert.AreEqual(3000, atomicCounter.Current); //should have a total count of 3000
            Assert.IsTrue(sharedFiber2.Running);
            Assert.IsTrue(originalFiber.Running);
            Assert.IsFalse(sharedFiber1.Running);
        }
Esempio n. 6
0
        public ActorRouteHandler(FiberFactory fiberFactory, ModelBinder modelBinder, ChannelProvider <TInput> channelProvider)
        {
            _modelBinder     = modelBinder;
            _channelProvider = channelProvider;

            _fiberFactory = fiberFactory;
        }
Esempio n. 7
0
        private static void Main(string[] args)
        {
            using (var system = ActorSystem.Create("TimeClient"))
            {
                var tmp = system.ActorSelection("akka.tcp://TimeServer@localhost:9391/user/time");
                Console.Title = string.Format("TimeClient {0}", Process.GetCurrentProcess().Id);
                var timeClient = system.ActorOf(Props.Create(() => new TimeClientActor(tmp)), "timeChecker");


                var fiber = FiberFactory.CreateFiber(3);

                while (!Program.IsShutdown)
                {
                    fiber.Add(() =>
                    {
                        Console.WriteLine("before sleep");
                        Thread.Sleep(3000);
                        timeClient.Tell(Time);
                    });
                }

                Console.WriteLine("Connection closed.");
                fiber.GracefulShutdown(TimeSpan.FromSeconds(1));

                Console.ReadLine();
                IsShutdown = true;
                Console.WriteLine("Shutting down...");
                Console.WriteLine("Terminated");
            }
        }
Esempio n. 8
0
 public RemoteActorRegistryBuilder(RegistryBuilder builder, Uri listenUri, FiberFactory fiberFactory,
                                   Func <Serializer> serializerFactory)
 {
     _builder           = builder;
     _serializerFactory = serializerFactory;
     _listenUri         = listenUri;
     _fiberFactory      = fiberFactory;
 }
Esempio n. 9
0
		public RemoteActorRegistryBuilder(RegistryBuilder builder, Uri listenUri, FiberFactory fiberFactory,
		                                  Func<Serializer> serializerFactory)
		{
			_builder = builder;
			_serializerFactory = serializerFactory;
			_listenUri = listenUri;
			_fiberFactory = fiberFactory;
		}
Esempio n. 10
0
 public IntervalChannelBuilder(ChannelBuilder <TChannel> builder, FiberFactory fiberFactory,
                               SchedulerFactory schedulerFactory, TimeSpan interval)
 {
     _builder          = builder;
     _interval         = interval;
     _schedulerFactory = schedulerFactory;
     _fiberFactory     = fiberFactory;
 }
Esempio n. 11
0
        static AnonymousActor()
        {
            _fiberFactory = () => new PoolFiber();

            _schedulerFactory = () => new TimerScheduler(new PoolFiber());

            CreateAnonymousActorFactory();
        }
Esempio n. 12
0
        public RemoteNodeCollection(FiberFactory fiberFactory, Scheduler scheduler, Serializer serializer)
        {
            _fiberFactory = fiberFactory;
            _scheduler    = scheduler;
            _serializer   = serializer;

            _nodes   = new Dictionary <string, Node>();
            _writers = new Dictionary <string, ChunkWriter>();
        }
Esempio n. 13
0
		public RemoteNodeCollection(FiberFactory fiberFactory, Scheduler scheduler, Serializer serializer)
		{
			_fiberFactory = fiberFactory;
			_scheduler = scheduler;
			_serializer = serializer;

			_nodes = new Dictionary<string, Node>();
			_writers = new Dictionary<string, ChunkWriter>();
		}
        public static Fiber GetFiberUsingConfiguredFactory <T, TChannel>(this FiberFactoryConfiguratorImpl <T> configurator,
                                                                         ConnectionBuilder <TChannel> builder)
            where T : class
        {
            FiberFactory fiberFactory = configurator.GetConfiguredFiberFactory();
            Fiber        fiber        = fiberFactory();

            builder.AddDisposable(fiber.ShutdownOnDispose(configurator.ShutdownTimeout));

            return(fiber);
        }
        protected FiberProvider <TKey> GetConfiguredFiberProvider()
        {
            if (_configuredProvider == null)
            {
                throw new FiberConfigurationException("No provider specified for FiberProvider");
            }

            FiberFactory fiberFactory = GetConfiguredFiberFactory();

            return(_configuredProvider(fiberFactory, ShutdownTimeout));
        }
Esempio n. 16
0
        public void Run()
        {
            Stopwatch timer = Stopwatch.StartNew();

            FiberFactory fiberFactory = () => new ThreadPoolFiber();

            const int channelCount = 10000;
            const int seedCount    = 500;

            var channels = new Channel <string> [channelCount];

            var complete = new Future <int>();

            var latch = new CountdownLatch(channelCount * seedCount, complete.Complete);

            for (int i = 0; i < channelCount; i++)
            {
                int channelNumber = i;
                channels[i] = new ConsumerChannel <string>(fiberFactory(), x =>
                {
                    if (channelNumber < channels.Length - 1)
                    {
                        channels[channelNumber + 1].Send(x);
                    }

                    latch.CountDown();
                });
            }

            for (int i = 0; i < seedCount; i++)
            {
                channels[i].Send("Hi");

                for (int j = 0; j < i; j++)
                {
                    latch.CountDown();
                }
            }

            bool completed = complete.WaitUntilCompleted(24.Seconds());

            timer.Stop();

            if (!completed)
            {
                Console.WriteLine("Process did not complete");
                return;
            }

            Console.WriteLine("Processed {0} messages in with {1} channels in {2}ms", seedCount, channelCount, timer.ElapsedMilliseconds);

            Console.WriteLine("That's {0} messages per second!", ((long)seedCount * channelCount * 1000) / timer.ElapsedMilliseconds);
        }
Esempio n. 17
0
        public void Should_use_multiple_threads_to_process_queue()
        {
            var atomicCounter = new AtomicCounter(0);
            var fiber         = FiberFactory.CreateFiber(2);

            for (var i = 0; i < 1000; i++)
            {
                fiber.Add(() => atomicCounter.GetAndIncrement());
            }
            fiber.GracefulShutdown(TimeSpan.FromSeconds(1)).Wait(); //wait for the fiber to finish
            Assert.AreEqual(1000, atomicCounter.Current);
        }
Esempio n. 18
0
        public void Run()
        {
            IFiberFactory factory             = new FiberFactory();
            int           OperationsPerInvoke = 1_000;

            using IChannel <string> _input  = new Channel <string>();
            using IChannel <string> _queue  = new QueueChannel <string>();
            using IChannel <string> _output = new Channel <string>();
            int count = 0;

            using AutoResetEvent reset = new AutoResetEvent(false);

            void Handler1(string x)
            {
                string u = x.ToUpper();

                _queue.Publish(u);
            }

            void Handler(string x)
            {
                string l = x.ToLower();

                _output.Publish(l);
            }

            void Action(string x)
            {
                int c = Interlocked.Increment(ref count);

                if (c >= OperationsPerInvoke)
                {
                    reset.Set();
                }
            }

            using ChannelAgent <string> fiber = new ChannelAgent <string>(factory, _input, Handler1);
            IDisposable[] middle = Enumerable.Range(0, 10)
                                   .Select(x => new ChannelAgent <string>(factory, _queue, Handler)).ToArray();
            using ChannelAgent <string> fiberOut = new ChannelAgent <string>(factory, _output, Action);

            for (int i = 0; i < OperationsPerInvoke; i++)
            {
                _input.Publish("a");
            }

            reset.WaitOne(TimeSpan.FromSeconds(20));
            foreach (IDisposable t in middle)
            {
                t.Dispose();
            }
        }
Esempio n. 19
0
        public RemoteNode(UntypedChannel input, ChunkWriter output, FiberFactory fiberFactory, Scheduler scheduler,
                          Serializer serializer)
        {
            _disposables = new List <IDisposable>();

            _scheduler = scheduler;

            _fiber = fiberFactory();

            _buffer = new BufferedChunkWriter(_fiber, _scheduler, output, 64 * 1024);
            _buffer.Start();

            _reader = new DeserializeChunkChannel(input, serializer);
            _writer = new SerializeChunkChannel(_buffer, serializer);
        }
Esempio n. 20
0
        public ActorRegistry CreateRegistry()
        {
            ValidateConfiguration();

            FiberFactory fiberFactory = GetConfiguredFiberFactory();
            Fiber        fiber        = fiberFactory();

            Scheduler scheduler = GetConfiguredScheduler();

            RegistryBuilder builder = _builderFactory(fiber, scheduler);

            return(_configurators
                   .Aggregate(builder, (current, configurator) => configurator.Configure(current))
                   .Build());
        }
Esempio n. 21
0
        public void Configure(ChannelBuilder <TChannel> builder)
        {
            FiberFactory fiberFactory = () =>
            {
                return(GetConfiguredFiber(builder));
            };

            SchedulerFactory schedulerFactory = () =>
            {
                return(GetConfiguredScheduler(builder));
            };

            var intervalBuilder = new IntervalChannelBuilder <TChannel>(builder, fiberFactory, schedulerFactory, _interval);

            _configurators.Each(x => x.Configure(intervalBuilder));
        }
Esempio n. 22
0
        public void Should_work()
        {
            Stopwatch timer = Stopwatch.StartNew();

            FiberFactory fiberFactory = () => new ThreadPoolFiber();

            const int channelCount = 10000;
            const int seedCount    = 500;

            var channels = new Channel <string> [channelCount];

            var completed = new Future <int>();

            var latch = new CountdownLatch(channelCount * seedCount, completed.Complete);

            for (int i = 0; i < channelCount; i++)
            {
                int channelNumber = i;
                channels[i] = new ConsumerChannel <string>(fiberFactory(), x =>
                {
                    if (channelNumber < channels.Length - 1)
                    {
                        channels[channelNumber + 1].Send(x);
                    }

                    latch.CountDown();
                });
            }

            for (int i = 0; i < seedCount; i++)
            {
                channels[i].Send("Hi");

                for (int j = 0; j < i; j++)
                {
                    latch.CountDown();
                }
            }

            completed.WaitUntilCompleted(24.Seconds()).ShouldBeTrue();

            timer.Stop();

            Trace.WriteLine("Elapsed Time: " + timer.ElapsedMilliseconds + "ms");
        }
        public void A_file_is_created()
        {
            _baseDirectory = AppDomain.CurrentDomain.BaseDirectory;

            string dir1 = Path.Combine(_baseDirectory, "dir1");
            string dir2 = Path.Combine(_baseDirectory, "dir2");

            if (System.IO.Directory.Exists(dir1))
            {
                System.IO.Directory.Delete(dir1, true);
            }

            if (System.IO.Directory.Exists(dir2))
            {
                System.IO.Directory.Delete(dir2, true);
            }

            System.IO.Directory.CreateDirectory(dir1);

            _createdListener = new Future <FileCreated>();
            _deletedListener = new Future <FileSystemDeleted>();

            _channel = new ChannelAdapter();
            FiberFactory fiberFactory = () => new SynchronousFiber();

            _scheduler = new TimerScheduler(fiberFactory());
            _producer  = new PollingFileSystemEventProducer(_baseDirectory, _channel, _scheduler, fiberFactory(),
                                                            20.Seconds());

            Thread.Sleep(5.Seconds());

            using (_channel.Connect(x =>
            {
                x.AddConsumerOf <FileCreated>().UsingConsumer(m => _createdListener.Complete(m));
                x.AddConsumerOf <FileSystemDeleted>().UsingConsumer(m => _deletedListener.Complete(m));
            }))
            {
                System.IO.Directory.Move(dir1, dir2);

                _createdListener.WaitUntilCompleted(10.Seconds());
                _deletedListener.WaitUntilCompleted(10.Seconds());
            }

            _producer.Dispose();
        }
Esempio n. 24
0
        private static void LoopWrite()
        {
            var command = Encoding.UTF8.GetBytes("gettime");
            var fiber   = FiberFactory.CreateFiber(3);

            Action dedicatedMethod = () =>
            {
                Thread.Sleep(1);
                TimeClient.Send(new NetworkData {
                    Buffer = command, Length = command.Length
                });
            };

            while (TimeClient.IsOpen())
            {
                fiber.Add(dedicatedMethod);
            }
            Console.WriteLine("Connection closed.");
            fiber.GracefulShutdown(TimeSpan.FromSeconds(1));
        }
Esempio n. 25
0
 private static void CreateAndWaitForWorkItems(int numWorkItems, int numThreads)
 {
     using (var mre = new ManualResetEvent(false))
         using (var fiber = FiberFactory.CreateFiber(numThreads))
         {
             var itemsRemaining = numWorkItems;
             for (var i = 0; i < numWorkItems; i++)
             {
                 fiber.Add(delegate
                 {
                     if (Interlocked.Decrement(
                             ref itemsRemaining) == 0)
                     {
                         mre.Set();
                     }
                 });
             }
             mre.WaitOne();
         }
 }
Esempio n. 26
0
        public void Should_not_be_able_to_add_jobs_after_shutdown()
        {
            var atomicCounter = new AtomicCounter(0);
            var fiber         = FiberFactory.CreateFiber(2);

            for (var i = 0; i < 1000; i++)
            {
                fiber.Add(() => atomicCounter.GetAndIncrement());
            }
            fiber.GracefulShutdown(TimeSpan.FromSeconds(1)).Wait(); //wait for the fiber to finish

            //try to increment the counter a bunch more times
            for (var i = 0; i < 1000; i++)
            {
                fiber.Add(() => atomicCounter.GetAndIncrement());
            }

            //value should be equal to its pre-shutdown value
            Assert.AreEqual(1000, atomicCounter.Current);
        }
Esempio n. 27
0
        public void Configure(ChannelBuilder <TChannel> builder)
        {
            FiberFactory fiberFactory = GetConfiguredFiberFactory();

            builder.AddChannel(fiberFactory(), fiber => new SelectiveConsumerChannel <TChannel>(fiber, _consumer));
        }
Esempio n. 28
0
 public SingleFiberProvider(FiberFactory factory, TimeSpan timeout)
 {
     _timeout = timeout;
     _fiber   = factory();
 }
Esempio n. 29
0
 public StandardActorConfiguration()
 {
     _fiberFactory = ThreadPoolFiberProvider;
     _actorFactory = null;
     _configure    = DefaultConfigureAction;
 }
Esempio n. 30
0
 public KeyedFiberProvider(FiberFactory missingFiberFactory, TimeSpan timeout)
 {
     _timeout = timeout;
     _cache   = new ConcurrentCache <TKey, Fiber>(k => missingFiberFactory());
 }
Esempio n. 31
0
 public RemoteNodeCollection(Uri inputAddress, UntypedChannel input, FiberFactory fiberFactory, Scheduler scheduler,
                             Serializer serializer)
     : this(fiberFactory, scheduler, serializer)
 {
     CreateLocalNode(inputAddress, input);
 }
        public T UseFiberFactory(FiberFactory fiberFactory)
        {
            _fiberFactory = executor => fiberFactory();

            return(this as T);
        }
Esempio n. 33
0
 public ThreadedEventLoop(int workerThreads) : base(FiberFactory.CreateFiber(workerThreads))
 {
 }
Esempio n. 34
0
 public ThreadedEventLoop(IExecutor internalExecutor, int workerThreads)
     : base(FiberFactory.CreateFiber(internalExecutor, workerThreads))
 {
 }
Esempio n. 35
0
		public RemoteNodeCollection(Uri inputAddress, UntypedChannel input, FiberFactory fiberFactory, Scheduler scheduler,
		                            Serializer serializer)
			: this(fiberFactory, scheduler, serializer)
		{
			CreateLocalNode(inputAddress, input);
		}
Esempio n. 36
0
		public RemoteRegistryNode(ActorRegistry registry, Uri listenUri, FiberFactory fiberFactory, Scheduler scheduler,
		                          Serializer serializer)
		{
			_nodes = new RemoteNodeCollection(listenUri, registry, fiberFactory, scheduler, serializer);
			_actors = new Dictionary<string, RemoteActor>();
		}