public void MTS_Foreach(int num, FMTS_DoForeach action) { if (EnableMTForeach == false) { for (int i = 0; i < num; i++) { action(i); } return; } int stride = num / ContextPools.Length; int remain = num % ContextPools.Length; unsafe { MTPSegment *segs = stackalloc MTPSegment[ContextPools.Length]; int startIndex = 0; for (int i = 0; i < ContextPools.Length; i++) { segs[i].Start = startIndex; startIndex += stride; segs[i].End = startIndex; } segs[ContextPools.Length - 1].End += remain; var smp = EngineNS.Thread.ASyncSemaphore.CreateSemaphore(ContextPools.Length, new System.Threading.AutoResetEvent(false)); for (int i = 0; i < ContextPools.Length; i++) { MTPSegment curSeg = segs[i]; CEngine.Instance.EventPoster.RunOn(() => { for (int j = curSeg.Start; j < curSeg.End; j++) { try { action(j); } catch (Exception ex) { Profiler.Log.WriteException(ex); } } smp.Release(); return(null); }, Thread.Async.EAsyncTarget.TPools); } smp.Wait(int.MaxValue); } }
private MTPSegment[] GetMultThreadSegement(int num) { int stride = num / ContextPools.Length; int remain = num % ContextPools.Length; var result = new MTPSegment[ContextPools.Length]; int startIndex = 0; for (int i = 0; i < ContextPools.Length; i++) { result[i].Start = startIndex; startIndex += stride; result[i].End = startIndex; } result[ContextPools.Length - 1].End += remain; return(result); }