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 -------------------- }
public ASyncThreadWorkData(IThreadWorkerObject[] workerObjects, bool safeMode, int maxWorkingThreads = -1) { if (workerObjects == null) return; workerPackages = new ThreadWorkStatePackage[workerObjects.Length]; int i = workerObjects.Length; while (--i > -1) { ThreadWorkStatePackage package = new ThreadWorkStatePackage(); package.waitHandle = new AutoResetEvent(false); package.workerObject = workerObjects[i]; package.safeMode = safeMode; workerPackages[i] = package; } if (maxWorkingThreads <= 0) { maxWorkingThreads = Mathf.Max(SystemInfo.processorCount - 1, 1); } else { this.maxWorkingThreads = maxWorkingThreads; } }
/// <summary> /// 解压释放单个文件 /// </summary> /// <param name="finishedObject"></param> private void onExtractDone(IThreadWorkerObject finishedObject) { LocalExtractExecutor lee = finishedObject as LocalExtractExecutor; // 文件本身 //PlayerPrefs.SetInt(lee.FileName , 1); //PlayerPrefs.SetString(lee.FileName + "_md5", lee.FileMD5); //解压出来的文件 foreach (string key in lee.SubFileMD5Dic.Keys) { PlayerPrefs.SetInt(key, 1); PlayerPrefs.SetString(key + "_md5", lee.SubFileMD5Dic[key]); } PlayerPrefs.Save(); extractFiles.Remove(lee.FileName); //Debugger.Log("正在解包文件:>" + lee.FileName); //监听解压进度 #if !UNITY_IOS var percent = (double)(totalExtractCount - extractFiles.Count) / (double)totalExtractCount; bar.SetMessage(string.Format("{0}:{1}%", LanguageTips.EXTRACT_PACKAGE, (percent * 100).ToString("f0"))); bar.UpdateProgress((float)percent); #endif Util.ClearMemory(); }
private IThreadWorkerObject[] GetWorkerObjectsFromPackages() { bool flag = this.workData == null || this.workData.workerPackages == null; IThreadWorkerObject[] result; if (flag) { result = new IThreadWorkerObject[0]; } else { IThreadWorkerObject[] array = new IThreadWorkerObject[this.workData.workerPackages.Length]; int num = this.workData.workerPackages.Length; while (true) { int num2 = num - 1; num = num2; if (num2 <= -1) { break; } array[num] = this.workData.workerPackages[num].workerObject; } result = array; } return(result); }
public void onPackageCompleteBubble(IThreadWorkerObject finishedObject) { if (onPackageComplete != null) { ThreadWorkDistribution <T> fCast = (ThreadWorkDistribution <T>)finishedObject; if (fCast != null) { onPackageComplete(fCast.workLoad, fCast.startIndex, fCast.endIndex - 1); } } }
public void onPackageCompleteBubble(IThreadWorkerObject finishedObject) { bool flag = this.onPackageComplete != null; if (flag) { ThreadWorkDistribution <T> threadWorkDistribution = (ThreadWorkDistribution <T>)finishedObject; bool flag2 = threadWorkDistribution != null; if (flag2) { this.onPackageComplete(threadWorkDistribution.workLoad, threadWorkDistribution.startIndex, threadWorkDistribution.endIndex - 1); } } }
private void StartResumingDownload(IThreadWorkerObject workerObj) { onResumingWorkerObjectDone(workerObj); if (resumingUpdates.Count > 0) { resumingUpdates.Remove(workerObj); } if (resumingUpdates.Count > 0) { resumingUpdates[0].ExecuteThreadedWork(); } else { onThreadWorkComplete(null); } }
private IThreadWorkerObject[] GetWorkerObjectsFromPackages() { if (workData == null || workData.workerPackages == null) { return(new IThreadWorkerObject[0]); } IThreadWorkerObject[] result = new IThreadWorkerObject[workData.workerPackages.Length]; int i = workData.workerPackages.Length; while (--i > -1) { result[i] = workData.workerPackages[i].workerObject; } return(result); }
/// <summary> /// 单个下载完成 /// </summary> /// <param name="finishedObject"></param> private void onWorkObjectDone(IThreadWorkerObject finishedObject) { ResumingUpdateExecutor updateExe = finishedObject as ResumingUpdateExecutor; Debugger.Log(string.Format("Download file>>{0}", updateExe.DownloadUrl)); downloadedSize += updateExe.FileSize; float percent = (float)downloadedSize / (float)totalSize; bar.SetMessage(string.Format("{0}({1}/{2})", LanguageTips.DOWNLOAD_FILE_ING, GameManager.GetSizeString(downloadedSize), GameManager.GetSizeString(totalSize))); bar.UpdateProgress(percent); downloadFiles.Add(updateExe.FileName); //检查下载文件的合法性,是否更新一致 if (!updateExe.SrcMD5.Equals(updateExe.DownloadFileMD5)) { if (!downloadErrorFiles.Contains(updateExe.FileName)) { downloadErrorFiles.Add(updateExe.FileName); } } else { if (downloadErrorFiles.Contains(updateExe.FileName)) { downloadErrorFiles.Remove(updateExe.FileName); } if (beginPackDownload) { Util.CallMethod("Game", "OnOnePackFileDownload", updateExe.LocalPath); } LuaHelper.GetGameManager().SetMd5(updateExe.FileName, updateExe.DownloadFileMD5, downloadFiles.Count % 3 == 0); } }
/// <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> public void StartASyncThreads(IThreadWorkerObject[] workerObjects, ThreadPoolSchedulerEvent onCompleteCallBack, ThreadedWorkCompleteEvent onPackageExecuted = null, int maxThreads = -1, bool safeMode = true) { MainThreadWatchdog.Init(); MainThreadDispatcher.Init(); if (_shedularBusy) { Debug.LogError("You are trying the start a new ASync threading-process, but is still Busy!"); return; } if (workerObjects == null || workerObjects.Length == 0) { Debug.LogError("Please provide an Array with atleast \"IThreadWorkerObject\"-object!"); return; } if (!ForceToMainThread) { _isAborted = false; this.onCompleteCallBack = onCompleteCallBack; this.onWorkerObjectDoneCallBack = onPackageExecuted; _shedularBusy = true; _providerThreadBusy = true; StartCoroutine("WaitForCompletion"); //--------------- Start Waiting for the Provider-thread to complete -------------------- workData = new ASyncThreadWorkData(workerObjects, safeMode, maxThreads); Thread providerThread = new Thread(new ThreadStart(InvokeASyncThreadPoolWork)); providerThread.Start(); //--------------- Start Waiting for the Provider-thread to complete -------------------- } else { //--------------- Execute all work in one bunch! -------------------- StartCoroutine(WaitAndExecuteWorkerObjects(workerObjects)); //--------------- Execute all work in one bunch! -------------------- } }
private IEnumerator WaitAndExecuteWorkerObjects(IThreadWorkerObject[] workerObjects) { _shedularBusy = true; yield return new WaitForEndOfFrame(); for (int i = 0; i < workerObjects.Length; i++) { workerObjects[i].ExecuteThreadedWork(); if (onWorkerObjectDoneCallBack != null) onWorkerObjectDoneCallBack(workerObjects[i]); } _shedularBusy = false; if (onCompleteCallBack != null) onCompleteCallBack(workerObjects); }
private void onThreadWorkComplete(IThreadWorkerObject[] finishedObjects) { flockingUpdateTime = Time.realtimeSinceStartup - flockingStartTime; flockingStartTime = Time.realtimeSinceStartup; //--------------- Resize arrays if needed -------------------- if (flockers.Length != FlockingSpawnCount) { int startCount = flockers.Length; System.Array.Resize(ref flockers, FlockingSpawnCount); ParticleSystem.Particle[] particles = new ParticleSystem.Particle[flockParticleEmitter.particleCount]; flockParticleEmitter.GetParticles(particles); System.Array.Resize(ref particles, FlockingSpawnCount); if (startCount < FlockingSpawnCount) { Vector3 center = this.transform.position; for (int i = startCount; i < FlockingSpawnCount; i++) { SpawnRandomFlockSpherical(center, flockers, i); SpawnNewParticle(particles, i); } } flockParticleEmitter.SetParticles(particles, particles.Length); if (myThreadScheduler != null) Destroy(myThreadScheduler.gameObject); //Reinit the threadpool InitThreadPool(); } else { //Restart the threadpool RestartThreadPoolWork(); } //--------------- Resize arrays if needed -------------------- }
//--------------- Managing a simple single Thread -------------------- //--------------- Managing a simple multithreaded ThreadPoolScheduler implementation -------------------- public void OnWorkerObjectDone(IThreadWorkerObject finishedObj) { LotsOfNumbers fCast = (LotsOfNumbers)finishedObj; Debug.LogWarning("Object done! result: " + fCast.result + ", maxIterations: " + fCast.maxIterations + ", ID: " + Thread.CurrentThread.ManagedThreadId + ", progress: " + (myThreadScheduler.Progress * 100f)); }
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 -------------------- }
//--------------- Managing a simple single Thread -------------------- //--------------- Managing a simple multithreaded ThreadPoolScheduler implementation -------------------- public void OnWorkerObjectDone(IThreadWorkerObject finishedObj) { LotsOfNumbers fCast = (LotsOfNumbers)finishedObj; Debug.LogWarning("Object done! result: " + fCast.result + ", maxIterations: " + fCast.maxIterations + ", ID: " + Thread.CurrentThread.ManagedThreadId + ", progress: " + (myThreadScheduler.Progress * 100f)); }
public void OnThreadWorkComplete(IThreadWorkerObject[] finishedObjects) { Debug.LogWarning("All work done! Managed Thread ID:" + Thread.CurrentThread.ManagedThreadId); }
private IThreadWorkerObject[] GetWorkerObjectsFromPackages() { if (workData == null || workData.workerPackages == null) return new IThreadWorkerObject[0]; IThreadWorkerObject[] result = new IThreadWorkerObject[workData.workerPackages.Length]; int i = workData.workerPackages.Length; while (--i > -1) result[i] = workData.workerPackages[i].workerObject; return result; }