暫無描述
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

IJobParallelForDefer.cs 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. using System;
  2. using Unity.Collections;
  3. using Unity.Collections.LowLevel.Unsafe;
  4. using Unity.Jobs.LowLevel.Unsafe;
  5. using System.Diagnostics;
  6. using Unity.Burst;
  7. namespace Unity.Jobs
  8. {
  9. /// <summary>
  10. /// Calculates the number of iterations to perform in a job that must execute before an IJobParallelForDefer job.
  11. /// </summary>
  12. /// <remarks>
  13. /// A replacement for IJobParallelFor when the number of work items is not known at Schedule time.
  14. ///
  15. /// When Scheduling the job's Execute(int index) method will be invoked on multiple worker threads in
  16. /// parallel to each other.
  17. ///
  18. /// Execute(int index) will be executed once for each index from 0 to the provided length. Each iteration
  19. /// must be independent from other iterations and the safety system enforces this rule for you. The indices
  20. /// have no guaranteed order and are executed on multiple cores in parallel.
  21. ///
  22. /// Unity automatically splits the work into chunks of no less than the provided batchSize, and schedules
  23. /// an appropriate number of jobs based on the number of worker threads, the length of the array and the batch size.
  24. ///
  25. /// Choose a batch size sbased on the amount of work performed in the job. A simple job,
  26. /// for example adding a couple of float3 to each other could have a batch size of 32 to 128. However,
  27. /// if the work performed is very expensive then it's best to use a small batch size, such as a batch
  28. /// size of 1. IJobParallelFor performs work stealing using atomic operations. Batch sizes can be
  29. /// small but they aren't free.
  30. ///
  31. /// The returned JobHandle can be used to ensure that the job has completed. Or it can be passed to other jobs as
  32. /// a dependency, ensuring that the jobs are executed one after another on the worker threads.
  33. /// </remarks>
  34. [JobProducerType(typeof(IJobParallelForDeferExtensions.JobParallelForDeferProducer<>))]
  35. public interface IJobParallelForDefer
  36. {
  37. /// <summary>
  38. /// Implement this method to perform work against a specific iteration index.
  39. /// </summary>
  40. /// <param name="index">The index of the Parallel for loop at which to perform work.</param>
  41. void Execute(int index);
  42. }
  43. /// <summary>
  44. /// Extension class for the IJobParallelForDefer job type providing custom overloads for scheduling and running.
  45. /// </summary>
  46. public static class IJobParallelForDeferExtensions
  47. {
  48. internal struct JobParallelForDeferProducer<T> where T : struct, IJobParallelForDefer
  49. {
  50. internal static readonly SharedStatic<IntPtr> jobReflectionData = SharedStatic<IntPtr>.GetOrCreate<JobParallelForDeferProducer<T>>();
  51. [BurstDiscard]
  52. internal static void Initialize()
  53. {
  54. if (jobReflectionData.Data == IntPtr.Zero)
  55. jobReflectionData.Data = JobsUtility.CreateJobReflectionData(typeof(T), (ExecuteJobFunction)Execute);
  56. }
  57. public delegate void ExecuteJobFunction(ref T jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex);
  58. public unsafe static void Execute(ref T jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex)
  59. {
  60. while (true)
  61. {
  62. if (!JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out int begin, out int end))
  63. break;
  64. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  65. JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), begin, end - begin);
  66. #endif
  67. // Cache the end value to make it super obvious to the
  68. // compiler that `end` will never change during the loops
  69. // iteration.
  70. var endThatCompilerCanSeeWillNeverChange = end;
  71. for (var i = begin; i < endThatCompilerCanSeeWillNeverChange; ++i)
  72. jobData.Execute(i);
  73. }
  74. }
  75. }
  76. /// <summary>
  77. /// Gathers and caches reflection data for the internal job system's managed bindings. Unity is responsible for calling this method - don't call it yourself.
  78. /// </summary>
  79. /// <typeparam name="T"></typeparam>
  80. /// <remarks>
  81. /// When the Jobs package is included in the project, Unity generates code to call EarlyJobInit at startup. This allows Burst compiled code to schedule jobs because the reflection part of initialization, which is not compatible with burst compiler constraints, has already happened in EarlyJobInit.
  82. ///
  83. /// __Note__: While the Jobs package code generator handles this automatically for all closed job types, you must register those with generic arguments (like IJobParallelForDefer&amp;lt;MyJobType&amp;lt;T&amp;gt;&amp;gt;) manually for each specialization with [[Unity.Jobs.RegisterGenericJobTypeAttribute]].
  84. /// </remarks>
  85. public static void EarlyJobInit<T>()
  86. where T : struct, IJobParallelForDefer
  87. {
  88. JobParallelForDeferProducer<T>.Initialize();
  89. }
  90. /// <summary>
  91. /// Schedule the job for execution on worker threads.
  92. /// list.Length is used as the iteration count.
  93. /// Note that it is required to embed the list on the job struct as well.
  94. /// </summary>
  95. /// <param name="jobData">The job and data to schedule.</param>
  96. /// <param name="list">list.Length is used as the iteration count.</param>
  97. /// <param name="innerloopBatchCount">Granularity in which workstealing is performed. A value of 32, means the job queue will steal 32 iterations and then perform them in an efficient inner loop.</param>
  98. /// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
  99. /// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
  100. /// <typeparam name="T">Job type</typeparam>
  101. /// <typeparam name="U">List element type</typeparam>
  102. public static unsafe JobHandle Schedule<T, U>(this T jobData, NativeList<U> list, int innerloopBatchCount,
  103. JobHandle dependsOn = new JobHandle())
  104. where T : struct, IJobParallelForDefer
  105. where U : unmanaged
  106. {
  107. void* atomicSafetyHandlePtr = null;
  108. // Calculate the deferred atomic safety handle before constructing JobScheduleParameters so
  109. // DOTS Runtime can validate the deferred list statically similar to the reflection based
  110. // validation in Big Unity.
  111. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  112. var safety = NativeListUnsafeUtility.GetAtomicSafetyHandle(ref list);
  113. atomicSafetyHandlePtr = UnsafeUtility.AddressOf(ref safety);
  114. #endif
  115. return ScheduleInternal(ref jobData, innerloopBatchCount,
  116. NativeListUnsafeUtility.GetInternalListDataPtrUnchecked(ref list),
  117. atomicSafetyHandlePtr, dependsOn);
  118. }
  119. /// <summary>
  120. /// Schedule the job for execution on worker threads.
  121. /// list.Length is used as the iteration count.
  122. /// Note that it is required to embed the list on the job struct as well.
  123. /// </summary>
  124. /// <param name="jobData">The job and data to schedule. In this variant, the jobData is
  125. /// passed by reference, which may be necessary for unusually large job structs.</param>
  126. /// <param name="list">list.Length is used as the iteration count.</param>
  127. /// <param name="innerloopBatchCount">Granularity in which workstealing is performed. A value of 32, means the job queue will steal 32 iterations and then perform them in an efficient inner loop.</param>
  128. /// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
  129. /// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
  130. /// <typeparam name="T">Job type</typeparam>
  131. /// <typeparam name="U">List element type</typeparam>
  132. public static unsafe JobHandle ScheduleByRef<T, U>(this ref T jobData, NativeList<U> list, int innerloopBatchCount,
  133. JobHandle dependsOn = new JobHandle())
  134. where T : struct, IJobParallelForDefer
  135. where U : unmanaged
  136. {
  137. void* atomicSafetyHandlePtr = null;
  138. // Calculate the deferred atomic safety handle before constructing JobScheduleParameters so
  139. // DOTS Runtime can validate the deferred list statically similar to the reflection based
  140. // validation in Big Unity.
  141. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  142. var safety = NativeListUnsafeUtility.GetAtomicSafetyHandle(ref list);
  143. atomicSafetyHandlePtr = UnsafeUtility.AddressOf(ref safety);
  144. #endif
  145. return ScheduleInternal(ref jobData, innerloopBatchCount,
  146. NativeListUnsafeUtility.GetInternalListDataPtrUnchecked(ref list),
  147. atomicSafetyHandlePtr, dependsOn);
  148. }
  149. /// <summary>
  150. /// Schedule the job for execution on worker threads.
  151. /// forEachCount is a pointer to the number of iterations, when dependsOn has completed.
  152. /// This API is unsafe, it is recommended to use the NativeList based Schedule method instead.
  153. /// </summary>
  154. /// <param name="jobData">The job and data to schedule.</param>
  155. /// <param name="forEachCount">*forEachCount is used as the iteration count.</param>
  156. /// <param name="innerloopBatchCount">Granularity in which workstealing is performed. A value of 32, means the job queue will steal 32 iterations and then perform them in an efficient inner loop.</param>
  157. /// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
  158. /// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
  159. /// <typeparam name="T">Job type</typeparam>
  160. /// <returns></returns>
  161. public static unsafe JobHandle Schedule<T>(this T jobData, int* forEachCount, int innerloopBatchCount,
  162. JobHandle dependsOn = new JobHandle())
  163. where T : struct, IJobParallelForDefer
  164. {
  165. var forEachListPtr = (byte*)forEachCount - sizeof(void*);
  166. return ScheduleInternal(ref jobData, innerloopBatchCount, forEachListPtr, null, dependsOn);
  167. }
  168. /// <summary>
  169. /// Schedule the job for execution on worker threads.
  170. /// forEachCount is a pointer to the number of iterations, when dependsOn has completed.
  171. /// This API is unsafe, it is recommended to use the NativeList based Schedule method instead.
  172. /// </summary>
  173. /// <param name="jobData">The job and data to schedule. In this variant, the jobData is
  174. /// passed by reference, which may be necessary for unusually large job structs.</param>
  175. /// <param name="forEachCount">*forEachCount is used as the iteration count.</param>
  176. /// <param name="innerloopBatchCount">Granularity in which workstealing is performed. A value of 32, means the job queue will steal 32 iterations and then perform them in an efficient inner loop.</param>
  177. /// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
  178. /// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
  179. /// <typeparam name="T"></typeparam>
  180. /// <returns></returns>
  181. public static unsafe JobHandle ScheduleByRef<T>(this ref T jobData, int* forEachCount, int innerloopBatchCount,
  182. JobHandle dependsOn = new JobHandle())
  183. where T : struct, IJobParallelForDefer
  184. {
  185. var forEachListPtr = (byte*)forEachCount - sizeof(void*);
  186. return ScheduleInternal(ref jobData, innerloopBatchCount, forEachListPtr, null, dependsOn);
  187. }
  188. private static unsafe JobHandle ScheduleInternal<T>(ref T jobData,
  189. int innerloopBatchCount,
  190. void* forEachListPtr,
  191. void *atomicSafetyHandlePtr,
  192. JobHandle dependsOn) where T : struct, IJobParallelForDefer
  193. {
  194. JobParallelForDeferProducer<T>.Initialize();
  195. var reflectionData = JobParallelForDeferProducer<T>.jobReflectionData.Data;
  196. CollectionHelper.CheckReflectionDataCorrect<T>(reflectionData);
  197. var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), reflectionData, dependsOn, ScheduleMode.Parallel);
  198. return JobsUtility.ScheduleParallelForDeferArraySize(ref scheduleParams, innerloopBatchCount, forEachListPtr, atomicSafetyHandlePtr);
  199. }
  200. }
  201. }