< Summary

Information
Class: Lattice.ECS.Core.Parallel.JobSystem
Assembly: Lattice
File(s): /home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Core/Parallel/JobSystem.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 92
Coverable lines: 92
Total lines: 267
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 34
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)0%4260%
ScheduleParallel(...)0%2040%
WaitForComplete(...)0%7280%
WorkerLoop(...)0%4260%
CalculateBatchSize(...)100%210%
Dispose()0%2040%
get_IsComplete()0%620%
.ctor()100%210%
Reset(...)100%210%
IncrementCompleted()100%210%
.ctor(...)100%210%
TryEnqueue(...)0%620%
TryDequeue(...)0%620%

File(s)

/home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Core/Parallel/JobSystem.cs

#LineLine coverage
 1// Copyright (c) 2026 Sideline Authors. All rights reserved.
 2// Licensed under GPL-3.0.
 3
 4using System;
 5using System.Runtime.CompilerServices;
 6using System.Threading;
 7using Lattice.Math;
 8
 9namespace 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
 24        public static readonly JobHandle Invalid = new(-1);
 25
 26        public JobHandle(int id)
 27        {
 28            Id = id;
 29            IsValid = id >= 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
 076        public JobSystem(int workerCount = -1)
 77        {
 078            WorkerCount = workerCount > 0 ? workerCount : Environment.ProcessorCount;
 079            _workers = new Thread[WorkerCount];
 080            _queue = new JobQueue(MaxJobs);
 081            _isRunning = true;
 82
 083            _completionStates = (JobCompletionState*)System.Runtime.InteropServices.Marshal.AllocHGlobal(
 084                sizeof(JobCompletionState) * MaxJobs).ToPointer();
 85
 086            for (int i = 0; i < MaxJobs; i++)
 087                _completionStates[i] = new JobCompletionState();
 88
 089            for (int i = 0; i < WorkerCount; i++)
 90            {
 091                _workers[i] = new Thread(WorkerLoop)
 092                {
 093                    Name = $"LatticeJobWorker-{i}",
 094                    IsBackground = true
 095                };
 096                _workers[i].Start(i);
 97            }
 098        }
 99
 100        public JobHandle ScheduleParallel(JobConfig config)
 101        {
 0102            int jobId = Interlocked.Increment(ref _jobIdCounter) - 1;
 0103            if (jobId >= MaxJobs)
 0104                throw new InvalidOperationException("Job limit exceeded");
 105
 0106            int batchSize = CalculateBatchSize(config.ElementCount, config.MinBatchSize);
 0107            int batchCount = (config.ElementCount + batchSize - 1) / batchSize;
 108
 0109            var handle = new JobHandle(jobId);
 0110            ref var state = ref _completionStates[jobId];
 0111            state.Reset(batchCount);
 112
 0113            for (int i = 0; i < batchCount; i++)
 114            {
 0115                int start = i * batchSize;
 0116                int end = System.Math.Min(start + batchSize, config.ElementCount);
 117
 0118                var batch = new JobBatch
 0119                {
 0120                    JobId = jobId,
 0121                    Delegate = config.Delegate,
 0122                    UserData = config.UserData,
 0123                    StartIndex = start,
 0124                    EndIndex = end
 0125                };
 126
 0127                _queue.TryEnqueue(batch);
 128            }
 129
 0130            return handle;
 131        }
 132
 133        public void WaitForComplete(JobHandle handle)
 134        {
 0135            if (!handle.IsValid) return;
 136
 0137            ref var state = ref _completionStates[handle.Id];
 138
 0139            int spinCount = 0;
 0140            while (!state.IsComplete && spinCount < 1000)
 141            {
 0142                Thread.SpinWait(10);
 0143                spinCount++;
 144            }
 145
 0146            if (!state.IsComplete)
 0147                state.WaitEvent.WaitOne();
 0148        }
 149
 150        private void WorkerLoop(object? state)
 151        {
 0152            while (_isRunning)
 153            {
 0154                if (_queue.TryDequeue(out var batch))
 155                {
 0156                    batch.Delegate(batch.UserData, batch.StartIndex, batch.EndIndex);
 157
 0158                    ref var completion = ref _completionStates[batch.JobId];
 0159                    if (completion.IncrementCompleted())
 0160                        completion.WaitEvent.Set();
 161                }
 162                else
 163                {
 0164                    Thread.Sleep(1);
 165                }
 166            }
 0167        }
 168
 169        private int CalculateBatchSize(int elementCount, int minBatchSize)
 170        {
 0171            int targetBatches = WorkerCount * 4;
 0172            return System.Math.Max(minBatchSize, (elementCount + targetBatches - 1) / targetBatches);
 173        }
 174
 175        public void Dispose()
 176        {
 0177            _isRunning = false;
 0178            foreach (var worker in _workers)
 0179                worker?.Join(1000);
 180
 0181            System.Runtime.InteropServices.Marshal.FreeHGlobal((IntPtr)_completionStates);
 0182        }
 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
 0201            public bool IsComplete => _completedCount >= _totalCount && _totalCount > 0;
 202
 203            public JobCompletionState()
 204            {
 0205                _completedCount = 0;
 0206                _totalCount = 0;
 0207                WaitEvent = new ManualResetEvent(false);
 0208            }
 209
 210            public void Reset(int totalCount)
 211            {
 0212                _completedCount = 0;
 0213                _totalCount = totalCount;
 0214                WaitEvent.Reset();
 0215            }
 216
 217            public bool IncrementCompleted()
 218            {
 0219                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
 0230            public JobQueue(int capacity)
 231            {
 0232                _capacity = capacity;
 0233                _buffer = (JobBatch*)System.Runtime.InteropServices.Marshal.AllocHGlobal(
 0234                    sizeof(JobBatch) * capacity).ToPointer();
 0235                _head = 0;
 0236                _tail = 0;
 0237            }
 238
 239            public bool TryEnqueue(in JobBatch batch)
 240            {
 0241                int currentTail = _tail;
 0242                int nextTail = (currentTail + 1) % _capacity;
 0243                if (nextTail == _head) return false;
 244
 0245                _buffer[currentTail] = batch;
 0246                _tail = nextTail;
 0247                return true;
 248            }
 249
 250            public bool TryDequeue(out JobBatch batch)
 251            {
 0252                int currentHead = _head;
 0253                if (currentHead == _tail)
 254                {
 0255                    batch = default;
 0256                    return false;
 257                }
 258
 0259                batch = _buffer[currentHead];
 0260                _head = (currentHead + 1) % _capacity;
 0261                return true;
 262            }
 263        }
 264
 265        #endregion
 266    }
 267}