The ReadOnly attribute lets you mark a member of a struct used in a job as read-only.
Native containers are read-write by default when used in a job. This means that you cannot schedule two jobs referencing the same containers simultaneously. By adding the ReadOnly attribute to the container field in the job struct the container is marked as read-only, which allows two jobs to run in parallel reading data from the same container.
See Also: 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 copy2.
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.