| | | 1 | | // Copyright (c) 2026 Sideline Authors. All rights reserved. |
| | | 2 | | // Licensed under GPL-3.0. |
| | | 3 | | |
| | | 4 | | using System; |
| | | 5 | | using System.Runtime.CompilerServices; |
| | | 6 | | using System.Threading; |
| | | 7 | | using Lattice.Math; |
| | | 8 | | |
| | | 9 | | namespace Lattice.ECS.Core.Parallel |
| | | 10 | | { |
| | | 11 | | /// <summary> |
| | | 12 | | /// 任务委托 - 多线程执行的回调 |
| | | 13 | | /// </summary> |
| | | 14 | | public unsafe delegate void JobDelegate(void* userData, int startIndex, int endIndex); |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// 任务句柄 - 用于依赖管理 |
| | | 18 | | /// </summary> |
| | | 19 | | public readonly struct JobHandle |
| | | 20 | | { |
| | | 21 | | public readonly int Id; |
| | | 22 | | public readonly bool IsValid; |
| | | 23 | | |
| | 0 | 24 | | public static readonly JobHandle Invalid = new(-1); |
| | | 25 | | |
| | | 26 | | public JobHandle(int id) |
| | | 27 | | { |
| | 0 | 28 | | Id = id; |
| | 0 | 29 | | IsValid = id >= 0; |
| | 0 | 30 | | } |
| | | 31 | | } |
| | | 32 | | |
| | | 33 | | /// <summary> |
| | | 34 | | /// 任务配置 |
| | | 35 | | /// </summary> |
| | | 36 | | public unsafe struct JobConfig |
| | | 37 | | { |
| | | 38 | | /// <summary>任务委托</summary> |
| | | 39 | | public JobDelegate Delegate; |
| | | 40 | | /// <summary>用户数据指针</summary> |
| | | 41 | | public void* UserData; |
| | | 42 | | /// <summary>元素总数(用于自动分片)</summary> |
| | | 43 | | public int ElementCount; |
| | | 44 | | /// <summary>最小分片大小</summary> |
| | | 45 | | public int MinBatchSize; |
| | | 46 | | /// <summary>依赖的任务</summary> |
| | | 47 | | public JobHandle Dependency; |
| | | 48 | | |
| | | 49 | | public static JobConfig Create(JobDelegate del, void* userData, int elementCount, int minBatchSize = 64) |
| | | 50 | | { |
| | | 51 | | return new JobConfig |
| | | 52 | | { |
| | | 53 | | Delegate = del, |
| | | 54 | | UserData = userData, |
| | | 55 | | ElementCount = elementCount, |
| | | 56 | | MinBatchSize = minBatchSize, |
| | | 57 | | Dependency = JobHandle.Invalid |
| | | 58 | | }; |
| | | 59 | | } |
| | | 60 | | } |
| | | 61 | | |
| | | 62 | | /// <summary> |
| | | 63 | | /// 简单任务系统 - 类似 FrameSync 的 TaskContext |
| | | 64 | | /// </summary> |
| | | 65 | | public unsafe class JobSystem : IDisposable |
| | | 66 | | { |
| | | 67 | | public readonly int WorkerCount; |
| | | 68 | | private const int MaxJobs = 1024; |
| | | 69 | | |
| | | 70 | | private readonly Thread[] _workers; |
| | | 71 | | private readonly JobQueue _queue; |
| | | 72 | | private volatile bool _isRunning; |
| | | 73 | | private int _jobIdCounter; |
| | | 74 | | private JobCompletionState* _completionStates; |
| | | 75 | | |
| | | 76 | | public JobSystem(int workerCount = -1) |
| | | 77 | | { |
| | | 78 | | WorkerCount = workerCount > 0 ? workerCount : Environment.ProcessorCount; |
| | | 79 | | _workers = new Thread[WorkerCount]; |
| | | 80 | | _queue = new JobQueue(MaxJobs); |
| | | 81 | | _isRunning = true; |
| | | 82 | | |
| | | 83 | | _completionStates = (JobCompletionState*)System.Runtime.InteropServices.Marshal.AllocHGlobal( |
| | | 84 | | sizeof(JobCompletionState) * MaxJobs).ToPointer(); |
| | | 85 | | |
| | | 86 | | for (int i = 0; i < MaxJobs; i++) |
| | | 87 | | _completionStates[i] = new JobCompletionState(); |
| | | 88 | | |
| | | 89 | | for (int i = 0; i < WorkerCount; i++) |
| | | 90 | | { |
| | | 91 | | _workers[i] = new Thread(WorkerLoop) |
| | | 92 | | { |
| | | 93 | | Name = $"LatticeJobWorker-{i}", |
| | | 94 | | IsBackground = true |
| | | 95 | | }; |
| | | 96 | | _workers[i].Start(i); |
| | | 97 | | } |
| | | 98 | | } |
| | | 99 | | |
| | | 100 | | public JobHandle ScheduleParallel(JobConfig config) |
| | | 101 | | { |
| | | 102 | | int jobId = Interlocked.Increment(ref _jobIdCounter) - 1; |
| | | 103 | | if (jobId >= MaxJobs) |
| | | 104 | | throw new InvalidOperationException("Job limit exceeded"); |
| | | 105 | | |
| | | 106 | | int batchSize = CalculateBatchSize(config.ElementCount, config.MinBatchSize); |
| | | 107 | | int batchCount = (config.ElementCount + batchSize - 1) / batchSize; |
| | | 108 | | |
| | | 109 | | var handle = new JobHandle(jobId); |
| | | 110 | | ref var state = ref _completionStates[jobId]; |
| | | 111 | | state.Reset(batchCount); |
| | | 112 | | |
| | | 113 | | for (int i = 0; i < batchCount; i++) |
| | | 114 | | { |
| | | 115 | | int start = i * batchSize; |
| | | 116 | | int end = System.Math.Min(start + batchSize, config.ElementCount); |
| | | 117 | | |
| | | 118 | | var batch = new JobBatch |
| | | 119 | | { |
| | | 120 | | JobId = jobId, |
| | | 121 | | Delegate = config.Delegate, |
| | | 122 | | UserData = config.UserData, |
| | | 123 | | StartIndex = start, |
| | | 124 | | EndIndex = end |
| | | 125 | | }; |
| | | 126 | | |
| | | 127 | | _queue.TryEnqueue(batch); |
| | | 128 | | } |
| | | 129 | | |
| | | 130 | | return handle; |
| | | 131 | | } |
| | | 132 | | |
| | | 133 | | public void WaitForComplete(JobHandle handle) |
| | | 134 | | { |
| | | 135 | | if (!handle.IsValid) return; |
| | | 136 | | |
| | | 137 | | ref var state = ref _completionStates[handle.Id]; |
| | | 138 | | |
| | | 139 | | int spinCount = 0; |
| | | 140 | | while (!state.IsComplete && spinCount < 1000) |
| | | 141 | | { |
| | | 142 | | Thread.SpinWait(10); |
| | | 143 | | spinCount++; |
| | | 144 | | } |
| | | 145 | | |
| | | 146 | | if (!state.IsComplete) |
| | | 147 | | state.WaitEvent.WaitOne(); |
| | | 148 | | } |
| | | 149 | | |
| | | 150 | | private void WorkerLoop(object? state) |
| | | 151 | | { |
| | | 152 | | while (_isRunning) |
| | | 153 | | { |
| | | 154 | | if (_queue.TryDequeue(out var batch)) |
| | | 155 | | { |
| | | 156 | | batch.Delegate(batch.UserData, batch.StartIndex, batch.EndIndex); |
| | | 157 | | |
| | | 158 | | ref var completion = ref _completionStates[batch.JobId]; |
| | | 159 | | if (completion.IncrementCompleted()) |
| | | 160 | | completion.WaitEvent.Set(); |
| | | 161 | | } |
| | | 162 | | else |
| | | 163 | | { |
| | | 164 | | Thread.Sleep(1); |
| | | 165 | | } |
| | | 166 | | } |
| | | 167 | | } |
| | | 168 | | |
| | | 169 | | private int CalculateBatchSize(int elementCount, int minBatchSize) |
| | | 170 | | { |
| | | 171 | | int targetBatches = WorkerCount * 4; |
| | | 172 | | return System.Math.Max(minBatchSize, (elementCount + targetBatches - 1) / targetBatches); |
| | | 173 | | } |
| | | 174 | | |
| | | 175 | | public void Dispose() |
| | | 176 | | { |
| | | 177 | | _isRunning = false; |
| | | 178 | | foreach (var worker in _workers) |
| | | 179 | | worker?.Join(1000); |
| | | 180 | | |
| | | 181 | | System.Runtime.InteropServices.Marshal.FreeHGlobal((IntPtr)_completionStates); |
| | | 182 | | } |
| | | 183 | | |
| | | 184 | | #region 内部结构 |
| | | 185 | | |
| | | 186 | | private struct JobBatch |
| | | 187 | | { |
| | | 188 | | public int JobId; |
| | | 189 | | public JobDelegate Delegate; |
| | | 190 | | public void* UserData; |
| | | 191 | | public int StartIndex; |
| | | 192 | | public int EndIndex; |
| | | 193 | | } |
| | | 194 | | |
| | | 195 | | private struct JobCompletionState |
| | | 196 | | { |
| | | 197 | | private volatile int _completedCount; |
| | | 198 | | private volatile int _totalCount; |
| | | 199 | | public readonly ManualResetEvent WaitEvent; |
| | | 200 | | |
| | | 201 | | public bool IsComplete => _completedCount >= _totalCount && _totalCount > 0; |
| | | 202 | | |
| | | 203 | | public JobCompletionState() |
| | | 204 | | { |
| | | 205 | | _completedCount = 0; |
| | | 206 | | _totalCount = 0; |
| | | 207 | | WaitEvent = new ManualResetEvent(false); |
| | | 208 | | } |
| | | 209 | | |
| | | 210 | | public void Reset(int totalCount) |
| | | 211 | | { |
| | | 212 | | _completedCount = 0; |
| | | 213 | | _totalCount = totalCount; |
| | | 214 | | WaitEvent.Reset(); |
| | | 215 | | } |
| | | 216 | | |
| | | 217 | | public bool IncrementCompleted() |
| | | 218 | | { |
| | | 219 | | return Interlocked.Increment(ref _completedCount) >= _totalCount; |
| | | 220 | | } |
| | | 221 | | } |
| | | 222 | | |
| | | 223 | | private unsafe class JobQueue |
| | | 224 | | { |
| | | 225 | | private readonly JobBatch* _buffer; |
| | | 226 | | private readonly int _capacity; |
| | | 227 | | private volatile int _head; |
| | | 228 | | private volatile int _tail; |
| | | 229 | | |
| | | 230 | | public JobQueue(int capacity) |
| | | 231 | | { |
| | | 232 | | _capacity = capacity; |
| | | 233 | | _buffer = (JobBatch*)System.Runtime.InteropServices.Marshal.AllocHGlobal( |
| | | 234 | | sizeof(JobBatch) * capacity).ToPointer(); |
| | | 235 | | _head = 0; |
| | | 236 | | _tail = 0; |
| | | 237 | | } |
| | | 238 | | |
| | | 239 | | public bool TryEnqueue(in JobBatch batch) |
| | | 240 | | { |
| | | 241 | | int currentTail = _tail; |
| | | 242 | | int nextTail = (currentTail + 1) % _capacity; |
| | | 243 | | if (nextTail == _head) return false; |
| | | 244 | | |
| | | 245 | | _buffer[currentTail] = batch; |
| | | 246 | | _tail = nextTail; |
| | | 247 | | return true; |
| | | 248 | | } |
| | | 249 | | |
| | | 250 | | public bool TryDequeue(out JobBatch batch) |
| | | 251 | | { |
| | | 252 | | int currentHead = _head; |
| | | 253 | | if (currentHead == _tail) |
| | | 254 | | { |
| | | 255 | | batch = default; |
| | | 256 | | return false; |
| | | 257 | | } |
| | | 258 | | |
| | | 259 | | batch = _buffer[currentHead]; |
| | | 260 | | _head = (currentHead + 1) % _capacity; |
| | | 261 | | return true; |
| | | 262 | | } |
| | | 263 | | } |
| | | 264 | | |
| | | 265 | | #endregion |
| | | 266 | | } |
| | | 267 | | } |