借助 ReadOnly 属性,您可以将作业中所用结构的某个成员标记为只读。
在作业中使用原生容器时,这些容器在默认情况下处于读写状态。这意味着,您无法同时安排两个作业来引用相同的容器。通过向作业结构中的容器字段添加 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(); } }
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.