将作业中使用的结构体成员标记为只读。
在作业中使用时,原生容器默认为读写。这意味着您无法同时安排两个引用相同容器的作业。在作业结构体中的原生容器字段中添加 ReadOnly 属性以将其标记为只读。这允许两个作业并行运行并从相同的原生容器读取数据。
其他资源:IJob,IJobParallelFor。
using Unity.Jobs; using Unity.Collections; using UnityEngine;
public struct MyJob : IJob { [ReadOnly] public NativeArray<int> input;
public NativeArray<int> output;
public void Execute() { for (var i = 0; i < output.Length; ++i) output[i] = input[i]; } }
public class ParallelReplicator : MonoBehaviour { public void OnUpdate() { const int n = 10000; var original = new NativeArray<int>(n, Allocator.Persistent); var clone1 = new NativeArray<int>(n, Allocator.Persistent); var clone2 = new NativeArray<int>(n, Allocator.Persistent);
var job1 = new MyJob { input = original, output = clone1 }; var job2 = new MyJob { input = original, output = clone2 };
var jobX = new MyJob { input = original, output = clone2 };
// Run the jobs in parallel. var jobs = JobHandle.CombineDependencies(job1.Schedule(), job2.Schedule());
// jobX.Schedule(); // Not allowed, throws exception because job2 is writing into clone2.
jobs.Complete();
jobX.Schedule().Complete(); // Allowed, because job2 has been completed by now.
original.Dispose(); clone1.Dispose(); clone2.Dispose(); } }