예제 #1
0
        void Awake()
        {
            ThreadPool.SetMaxThreads(1, 1);

            PoolScheduler = Loom.CreateThreadPoolScheduler("_ThreadPoolScheduler");
            DontDestroyOnLoad(PoolScheduler.gameObject);
        }
예제 #2
0
    void Awake()
    {
        Application.targetFrameRate = 25;
        myThreadScheduler           = Loom.CreateThreadPoolScheduler();

        //--------------- Ending Single threaded routine --------------------
        threadA = Loom.StartSingleThread(EndingSingleThreadCoroutine, System.Threading.ThreadPriority.Normal, true);
        //--------------- Ending Single threaded routine --------------------

        //--------------- Continues Single threaded routine --------------------
        threadB = Loom.StartSingleThread(ContinuesSingleThreadCoroutine, System.Threading.ThreadPriority.Normal, true);
        //--------------- Continues Single threaded routine --------------------

        //--------------- Start Multithreaded packages --------------------
        int i = TestWorkerObjects;

        IThreadWorkerObject[] workerObjects = new IThreadWorkerObject[TestWorkerObjects];

        while (--i > -1)
        {
            workerObjects[i] = new LotsOfNumbers(UnityEngine.Random.Range(minCalculations, maxCalculations));
        }

        myThreadScheduler.StartASyncThreads(workerObjects, OnThreadWorkComplete, OnWorkerObjectDone, maxThreads);
        StartCoroutine(AbortAllThreadsAfterDelay());
        //--------------- Start Multithreaded packages --------------------
    }
예제 #3
0
        public void Schedule1000In1ms()
        {
            var queue = new SynchronousCommandQueue();
            queue.Run();

            var count = 0;
            var reset = new AutoResetEvent(false);
            Action one = delegate
                {
                    count++;
                    if (count == 1000)
                    {
                        reset.Set();
                    }
                };

            using (var thread = new ThreadPoolScheduler())
            {
                for (var i = 0; i < 1000; i++)
                {
                    thread.Schedule(i, () => queue.Enqueue(one));
                }
                Assert.IsTrue(reset.WaitOne(1200, false));
            }
        }
예제 #4
0
    void Start()
    {
        myScheduler = Loom.CreateThreadPoolScheduler("myScheduler");

        displayTexture = new Texture2D(Texture.width, Texture.height, TextureFormat.ARGB32, false);
        textureWidth   = Texture.width;
        textureHeight  = Texture.height;

        origionalColors   = Texture.GetPixels32();
        sourcePixels      = new Pixel[origionalColors.Length];
        sourceColors      = new Color32[origionalColors.Length];
        destinationColors = new Color32[origionalColors.Length];

        int i = 0;

        for (int y = 0; y < Texture.height; y++)
        {
            for (int x = 0; x < Texture.width; x++)
            {
                sourcePixels[i] = new Pixel(x, y);
                i++;
            }
        }

        myScheduler.ForceToMainThread = !MultithreadingEnabled;
        StartBluringTexture();
    }
예제 #5
0
 /// <summary>This constructor should be hidden from the outside</summary>
 private DefaultActorSystemFactory()
 {
     UniqueNameCreator      = new UniqueNameCreator();
     LocalActorRefFactory   = new DefaultLocalActorRefFactory();
     DeadLetterActorCreator = (path, system) => new DeadLetterActorRef(path, system);
     Scheduler             = new ThreadPoolScheduler();
     DefaultMailboxCreator = scheduler => new UnboundedMailbox(scheduler);
 }
예제 #6
0
 public SchedulerProvider()
 {
     Task = new TaskScheduler();
     IOCompletion = new IOCompletionScheduler();
     Current = new CurrentScheduler();
     Immediate = new ImmediateScheduler();
     NewThread = new NewThreadScheduler();
     ThreadPool = new ThreadPoolScheduler();
 }
예제 #7
0
        public void Timer_Based_Demo()
        {
            ThreadPoolScheduler scheduler = new ThreadPoolScheduler();
            scheduler.Schedule(0, 1000, ()=>
                {
                    Trace.WriteLine("Starting it up");
                    _ping.Start(10, _pong);
                });

            Thread.Sleep(6000);
        }
예제 #8
0
        public void Start(IServiceBus bus)
        {
            _unsubscribeAction = bus.Subscribe <WorkerAvailable <T> >(Consume);

            // don't plan to unsubscribe this since it's an important thing
            bus.Subscribe(this);

            _threadPoolScheduler = new ThreadPoolScheduler();

            _threadPoolScheduler.Schedule(_pingTimeout, _pingTimeout, PingWorkers);
        }
예제 #9
0
        public void Start(IServiceBus bus)
        {
            _bus        = bus;
            _controlBus = bus.ControlBus;

            _dataUri    = _bus.Endpoint.Uri;
            _controlUri = _controlBus.Endpoint.Uri;

            _unsubscribeAction  = bus.ControlBus.Subscribe <ConfigureWorker>(Consume, Accept);
            _unsubscribeAction += bus.ControlBus.Subscribe <PingWorker>(Consume);
            _unsubscribeAction += bus.Subscribe(this);

            _threadPoolScheduler = new ThreadPoolScheduler();

            _threadPoolScheduler.Schedule((int)3.Seconds().TotalMilliseconds, (int)1.Minutes().TotalMilliseconds, PublishWorkerAvailability);
        }
예제 #10
0
 public void TimeTilNext()
 {
     var queue = new SynchronousCommandQueue();
     queue.Run();
     Action action = () => Assert.Fail("Should not execute");
     using (var timer = new ThreadPoolScheduler())
     {
         long now = 0;
         long span = 0;
         timer.QueueEvent(new SingleEvent(500, () => queue.Enqueue(action), now));
         Assert.IsTrue(timer.GetNextScheduledTime(ref span, 0));
         Assert.AreEqual(500, span);
         Assert.IsTrue(timer.GetNextScheduledTime(ref span, 499));
         Assert.AreEqual(1, span);
         Assert.IsFalse(timer.GetNextScheduledTime(ref span, 500));
         Assert.AreEqual(0, span);
     }
 }
예제 #11
0
        /**
         * Scheduler控制订阅和通知的发送。
         * Scheduler包含三个组件:1)一个优先队列存放任务,2)Execution context,用来决定任务在哪执行(线程池,当前线程)3)scheduler的时钟,Task是根据这个时钟调度的,不是系统时钟。
         *
         * rx中所有的Scheduler实现IScheduler接口。
         *
         */

        public static void GetSchedulers()
        {
            //立刻在当前线程上执行
            ImmediateScheduler immediate = Scheduler.Immediate;
            //在当前线程上尽可能快的执行(先放到队列中,尽快执行)
            CurrentThreadScheduler currentThreadScheduler = Scheduler.CurrentThread;
            //每次创建一个线程执行
            NewThreadScheduler newThreadScheduler = NewThreadScheduler.Default;
            //在Task Factory上执行
            TaskPoolScheduler taskPoolScheduler = TaskPoolScheduler.Default;

            //在当前Dispatcher上执行任务
            DispatcherScheduler dispatcherScheduler = DispatcherScheduler.Current;

            //在ThreadPool上执行
            ThreadPoolScheduler threadPoolScheduler = ThreadPoolScheduler.Instance;
            //默认的调度器  其原则是使用最小的并行性,for operators returning an observable with a finite and small number of messages, Rx calls Immediate.  For operators returning a potentially large or infinite number of messages, CurrentThread is called. For operators which use timers, ThreadPool is used.
            DefaultScheduler defaultScheduler = Scheduler.Default;
        }
예제 #12
0
        public void Should_schedule_events()
        {
            Channel<UserUpdate> channel = new SynchronousChannel<UserUpdate>();

            var update = new UserUpdate {LastActivity = DateTime.Now - 5.Minutes()};

            CommandQueue queue = new SynchronousCommandQueue();

            var scheduler = new ThreadPoolScheduler();

            var future = new Future<UserUpdate>();

            channel.Subscribe(queue, future.Complete);

            scheduler.Schedule(1000, () => channel.Publish(update));

            Thread.Sleep(500);

            Assert.IsFalse(future.IsAvailable(0.Seconds()));

            Assert.IsTrue(future.IsAvailable(1.Seconds()));
        }
예제 #13
0
        public void Schedule()
        {
            var queue = new SynchronousCommandQueue();

            var count = 0;
            var reset = new AutoResetEvent(false);
            Action one = () => Assert.AreEqual(0, count++);
            Action two = () => Assert.AreEqual(1, count++);
            Action three = delegate
                {
                    Assert.AreEqual(2, count++);
                    reset.Set();
                };

            using (var thread = new ThreadPoolScheduler())
            {
                thread.Schedule(50, () => queue.Enqueue(three));
                thread.Schedule(1, () => queue.Enqueue(one));
                thread.Schedule(1, () => queue.Enqueue(two));
                Assert.IsTrue(reset.WaitOne(10000, false));
            }
        }
예제 #14
0
    private void InitThreadPool()
    {
        //--------------- Cap the number of threads --------------------
        int maxThreads = ThreadingMaxThreads;

        if (maxThreads <= 0)
        {
            maxThreads = Mathf.Max(SystemInfo.processorCount - 1, 1);
        }
        //--------------- Cap the number of threads --------------------

        //--------------- Spread the Flocks over multiple worker-packages --------------------
        int ThreadingPoolPackages = ThreadingPackagesPerThread * maxThreads;

        int flocksPerBlock = Mathf.CeilToInt((float)FlockingSpawnCount / (float)ThreadingPoolPackages);

        workerObjects = new FlockingDataWorker[ThreadingPoolPackages];

        int i        = ThreadingPoolPackages;
        int startIdx = 0;

        while (--i > -1)
        {
            FlockingDataWorker workerBlock = new FlockingDataWorker();
            UpdateWorkerObjectStats(workerBlock);

            workerBlock.startWorkIndex = startIdx;
            workerBlock.endWorkIndex   = Mathf.Min(flockers.Length, startIdx + flocksPerBlock);
            workerObjects[i]           = workerBlock;
            startIdx += flocksPerBlock;
        }
        //--------------- Spread the Flocks over multiple worker-packages --------------------


        myThreadScheduler = Loom.CreateThreadPoolScheduler();
        myThreadScheduler.ForceToMainThread = !MultithreadingEnabled;
        myThreadScheduler.StartASyncThreads(workerObjects, onThreadWorkComplete, null, maxThreads);
    }
예제 #15
0
    void Start()
    {
        DontDestroyOnLoad(this);
        myThreadScheduler = UThread.CreateThreadPoolScheduler();
        //myThreadScheduler.ForceToMainThread = true;
        //UThread.StartSingleThread(LoadConfig, System.Threading.ThreadPriority.Normal, true);
        workerObjects = new FlockingDataWorker[1];
        int maxThreads = -1;

        if (maxThreads <= 0)
        {
            maxThreads = Mathf.Max(SystemInfo.processorCount - 1, 1);
        }

        FlockingDataWorker workerBlock = new FlockingDataWorker();

        workerObjects[0] = workerBlock;

        myThreadScheduler.ForceToMainThread = true;
        myThreadScheduler.StartASyncThreads(workerObjects, onThreadWorkComplete, null, maxThreads);

        StartCoroutine(LoadPosFile());
        StartCoroutine(LoadSummonPosFile());
    }
예제 #16
0
 public ThreadPoolPriorityScheduler()
 {
     _lowScheduler    = new ThreadPoolScheduler(WorkItemPriority.Low);
     _normalScheduler = new ThreadPoolScheduler(WorkItemPriority.Normal);
     _highScheduler   = new ThreadPoolScheduler(WorkItemPriority.High);
 }
예제 #17
0
        /// <summary>
        /// Helps spreading the same repetetive workload over multiple threads/cores in an easy way.
        /// </summary>
        /// <typeparam name="D">Generic-Type of the delegate that will be executed and compute the workload</typeparam>
        /// <typeparam name="T">Generic-Type of the object you want to be computed by the executor</typeparam>
        /// <param name="executor">A (static) method that computes one workLoad-object at a time</param>
        /// <param name="workLoad">An array with objects you want to get computed by the executor</param>
        /// <param name="onComplete">Fired when all re-packaged workLoad-objects are finished computing</param>
        /// <param name="onPackageComplete">Fires foreach finished re-packaged set of workLoad-object</param>
        /// <param name="maxThreads"> Lets you choose how many threads will be run simultaneously by the threadpool. Default: -1 == number of cores minus one, to make sure the MainThread has at least one Core to run on. (quadcore == 1 Core Mainthread, 3 cores used by the ThreadPoolScheduler)</param>
        /// <param name="scheduler">If Null, a new ThreadPoolScheduler will be instantiated.</param>
        /// <param name="safeMode">Executes all the computations within try-catch events, logging it the message + stacktrace</param>
        /// <returns>A ThreadPoolScheduler that handles all the repackaged workLoad-Objects =</returns>
        public static ThreadPoolScheduler StartMultithreadedWorkloadExecution <D, T>(D executor, T[] workLoad, object extraArgument, MultithreadedWorkloadComplete <T> onComplete, MultithreadedWorkloadPackageComplete <T> onPackageComplete, int maxThreads = -1, ThreadPoolScheduler scheduler = null, bool safeMode = true)
        {
            if (scheduler == null)
            {
                scheduler = Loom.CreateThreadPoolScheduler();
            }
            else if (scheduler.isBusy)
            {
                Debug.LogError("Provided Scheduler stil busy!!!");
            }

            if (maxThreads <= 0)
            {
                maxThreads = Mathf.Max(SystemInfo.processorCount - 1, 1);
            }

            int packagesPerThread = 1;

            if (maxThreads > 1) //If we are running in just one thread at a time, just use one, if more, for sake of better cpu-saturation, subdive into smaller packages per Core.
            {
                packagesPerThread = 2;
            }

            int packages          = Mathf.Min(maxThreads * packagesPerThread, workLoad.Length);
            int objectsPerPackage = (int)Mathf.Ceil((float)workLoad.Length / (float)packages);

            ThreadWorkDistribution <T>[] workerPackages = new ThreadWorkDistribution <T> [packages];
            Type delegateType = typeof(D);
            //Debug.Log(delegateType.FullName);

            int count = 0;

            for (int i = 0; i < packages; i++)
            {
                int packagedSize = Mathf.Min(workLoad.Length - count, objectsPerPackage);
                if (delegateType == typeof(ThreadWorkloadExecutor <T>))
                {
                    workerPackages[i] = new ThreadWorkDistribution <T>((executor as ThreadWorkloadExecutor <T>), workLoad, count, count + packagedSize);
                }
                else if (delegateType == typeof(ThreadWorkloadExecutorIndexed <T>))
                {
                    workerPackages[i] = new ThreadWorkDistribution <T>((executor as ThreadWorkloadExecutorIndexed <T>), workLoad, count, count + packagedSize);
                }
                else if (delegateType == typeof(ThreadWorkloadExecutorArg <T>))
                {
                    workerPackages[i] = new ThreadWorkDistribution <T>((executor as ThreadWorkloadExecutorArg <T>), workLoad, extraArgument, count, count + packagedSize);
                }
                else if (delegateType == typeof(ThreadWorkloadExecutorArgIndexed <T>))
                {
                    workerPackages[i] = new ThreadWorkDistribution <T>((executor as ThreadWorkloadExecutorArgIndexed <T>), workLoad, extraArgument, count, count + packagedSize);
                }

                workerPackages[i].ID = i;
                count += objectsPerPackage;
            }



            //--------------- Store session data --------------------
            ThreadWorkDistributionSession <T> sessionData = new ThreadWorkDistributionSession <T>();

            sessionData.workLoad          = workLoad;
            sessionData.onComplete        = onComplete;
            sessionData.onPackageComplete = onPackageComplete;
            sessionData.packages          = workerPackages;
            //--------------- Store session data --------------------


            scheduler.StartASyncThreads(workerPackages, sessionData.onCompleteBubble, sessionData.onPackageCompleteBubble, maxThreads, safeMode);
            return(scheduler);
        }
예제 #18
0
    //--------------------------------------- 4 MULTI THREADED WORK EXECUTION OVERLOADS --------------------------------------
    //--------------------------------------- 4 MULTI THREADED WORK EXECUTION OVERLOADS --------------------------------------



    //--------------------------------------- THREAD POOL SCHEDULAR --------------------------------------
    //--------------------------------------- THREAD POOL SCHEDULAR --------------------------------------

    #region THREAD POOL SCHEDULAR


    /// <summary>
    /// Unlike "StartMultithreadedWorkloadExecution", you will have to build your own IThreadWorkerObject.
    /// Downside: It requires some extra work. Upside: you got more controll over what goes in and comes out
    /// Infact: You can create you own polymorphed IThreadWorkerObject-array, each ellement being a completely different type. For example: the statemachines of enemies are IThreadWorkerObject's and the array contains completely different classes with enemies/AI-behaviours.
    /// </summary>
    /// <param name="workerObjects">An array of IThreadWorkerObject objects to be handled by the threads. If you want multiple cores/threads to be active, make sure that the number of IThreadWorkerObject's proves matches/exeeds your preferred number maxWorkingThreads. </param>
    /// <param name="onComplete">Fired when all re-packaged workLoad-objects are finished computing</param>
    /// <param name="onPackageExecuted">Fires foreach finished re-packaged set of workLoad-object</param>
    /// <param name="maxThreads"> Lets you choose how many threads will be run simultaneously by the threadpool. Default: -1 == number of cores minus one, to make sure the MainThread has at least one Core to run on. (quadcore == 1 Core Mainthread, 3 cores used by the ThreadPoolScheduler)</param>
    /// <param name="scheduler">If Null, a new ThreadPoolScheduler will be instantiated.</param>
    /// <param name="safeMode">Executes all the computations within try-catch events, logging it the message + stacktrace</param>
    /// <returns>A ThreadPoolScheduler that handles all the repackaged workLoad-Objects</returns>
    public static ThreadPoolScheduler StartMultithreadedWorkerObjects(IThreadWorkerObject[] workerObjects, ThreadPoolSchedulerEvent onCompleteCallBack, ThreadedWorkCompleteEvent onPackageExecuted = null, int maxThreads = -1, ThreadPoolScheduler scheduler = null, bool safeMode = true)
    {
        if (scheduler == null)
        {
            scheduler = CreateThreadPoolScheduler();
        }

        scheduler.StartASyncThreads(workerObjects, onCompleteCallBack, onPackageExecuted, maxThreads, safeMode);
        return(scheduler);
    }
예제 #19
0
 /// <summary>
 /// Helps spreading the same repetetive workload over multiple threads/cores in an easy way.
 /// Besides the workLoad-object, an extra Argument & the current index of the workLoad-array is passed to the Executor-delegate.
 /// </summary>
 /// <typeparam name="T">T: Generic-Type of the object you want to be computed by the executor</typeparam>
 /// <param name="staticWorkloadExecutor"> A (static) method that computes one workLoad-object at a time</param>
 /// <param name="workLoad">An array with objects you want to get computed by the executor</param>
 /// <param name="onComplete">Fired when all re-packaged workLoad-objects are finished computing</param>
 /// <param name="onPackageExecuted">Fires foreach finished re-packaged set of workLoad-object</param>
 /// <param name="maxThreads"> Lets you choose how many threads will be run simultaneously by the threadpool. Default: -1 == number of cores minus one, to make sure the MainThread has at least one Core to run on. (quadcore == 1 Core Mainthread, 3 cores used by the ThreadPoolScheduler)</param>
 /// <param name="scheduler">If Null, a new ThreadPoolScheduler will be instantiated.</param>
 /// <param name="safeMode">Executes all the computations within try-catch events, logging it the message + stacktrace</param>
 /// <returns>A ThreadPoolScheduler that handles all the repackaged workLoad-Objects</returns>
 public static ThreadPoolScheduler StartMultithreadedWorkloadExecution <T>(ThreadWorkloadExecutorArgIndexed <T> workloadExecutor, T[] workLoad, object extraArgument, MultithreadedWorkloadComplete <T> onComplete, MultithreadedWorkloadPackageComplete <T> onPackageComplete, int maxThreads = -1, ThreadPoolScheduler scheduler = null, bool safeMode = true)
 {
     return(MultithreadedWorkloadHelper.StartMultithreadedWorkloadExecution <ThreadWorkloadExecutorArgIndexed <T>, T>(workloadExecutor, workLoad, extraArgument, onComplete, onPackageComplete, maxThreads, scheduler, safeMode));
 }
예제 #20
0
 public Bus()
 {
     Subject   = new Subject <Message>();
     Scheduler = ThreadPoolScheduler.Instance;
 }
 public ThreadPoolSchedulerTests()
 {
     this.handler = new Mock <Action <object> >();
     this.subject = new ThreadPoolScheduler();
 }
        public static ThreadPoolScheduler StartMultithreadedWorkloadExecution <D, T>(D executor, T[] workLoad, object extraArgument, MultithreadedWorkloadComplete <T> onComplete, MultithreadedWorkloadPackageComplete <T> onPackageComplete, int maxThreads = -1, ThreadPoolScheduler scheduler = null, bool safeMode = true)
        {
            bool flag = scheduler == null;

            if (flag)
            {
                scheduler = Loom.CreateThreadPoolScheduler();
            }
            else
            {
                bool isBusy = scheduler.isBusy;
                if (isBusy)
                {
                    Debug.LogError("Provided Scheduler stil busy!!!");
                }
            }
            bool flag2 = maxThreads <= 0;

            if (flag2)
            {
                maxThreads = Mathf.Max(SystemInfo.processorCount - 1, 1);
            }
            int  num   = 1;
            bool flag3 = maxThreads > 1;

            if (flag3)
            {
                num = 2;
            }
            int num2 = Mathf.Min(maxThreads * num, workLoad.Length);
            int num3 = (int)Mathf.Ceil((float)workLoad.Length / (float)num2);

            ThreadWorkDistribution <T>[] array = new ThreadWorkDistribution <T> [num2];
            Type typeFromHandle = typeof(D);
            int  num4           = 0;
            int  num6;

            for (int i = 0; i < num2; i = num6 + 1)
            {
                int  num5  = Mathf.Min(workLoad.Length - num4, num3);
                bool flag4 = typeFromHandle == typeof(ThreadWorkloadExecutor <T>);
                if (flag4)
                {
                    array[i] = new ThreadWorkDistribution <T>(executor as ThreadWorkloadExecutor <T>, workLoad, num4, num4 + num5);
                }
                else
                {
                    bool flag5 = typeFromHandle == typeof(ThreadWorkloadExecutorIndexed <T>);
                    if (flag5)
                    {
                        array[i] = new ThreadWorkDistribution <T>(executor as ThreadWorkloadExecutorIndexed <T>, workLoad, num4, num4 + num5);
                    }
                    else
                    {
                        bool flag6 = typeFromHandle == typeof(ThreadWorkloadExecutorArg <T>);
                        if (flag6)
                        {
                            array[i] = new ThreadWorkDistribution <T>(executor as ThreadWorkloadExecutorArg <T>, workLoad, extraArgument, num4, num4 + num5);
                        }
                        else
                        {
                            bool flag7 = typeFromHandle == typeof(ThreadWorkloadExecutorArgIndexed <T>);
                            if (flag7)
                            {
                                array[i] = new ThreadWorkDistribution <T>(executor as ThreadWorkloadExecutorArgIndexed <T>, workLoad, extraArgument, num4, num4 + num5);
                            }
                        }
                    }
                }
                array[i].ID = i;
                num4       += num3;
                num6        = i;
            }
            ThreadWorkDistributionSession <T> threadWorkDistributionSession = new ThreadWorkDistributionSession <T>();

            threadWorkDistributionSession.workLoad          = workLoad;
            threadWorkDistributionSession.onComplete        = onComplete;
            threadWorkDistributionSession.onPackageComplete = onPackageComplete;
            threadWorkDistributionSession.packages          = array;
            scheduler.StartASyncThreads(array, new ThreadPoolSchedulerEvent(threadWorkDistributionSession.onCompleteBubble), new ThreadedWorkCompleteEvent(threadWorkDistributionSession.onPackageCompleteBubble), maxThreads, safeMode);
            return(scheduler);
        }
예제 #23
0
 public void TimeTilNextNothingQueued()
 {
     using (var timer = new ThreadPoolScheduler())
     {
         long result = 0;
         Assert.IsFalse(timer.GetNextScheduledTime(ref result, 100));
         Assert.AreEqual(0, result);
     }
 }