How to read and write to the same NativeList.

Inside Job struct I declare it like this
NativeList timeToIsFalling;
no read and write only attributes since I want to update it’s value every frame (in a job).

Unfortunately during runtime I get an exception:

InvalidOperationException: Job.timeToIsFalling is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing. Please use a more suitable container type.

There is a parrallelWriter (AsParallelWriter) for the native list, you need to use this to write to the native list in a parrallel context.

Unfortunalty, I think this will prevent you from reading from that list too with the AsParallelReader has it would result in confilct were one thread could read from a value you are writting to in another one.

So you will either need to make a copy of your list to read from and keep the parrallel writer to write the updates or you could make your job single threaded and there should be no error anymore.

AsParallelWriter is only from parallel Add it does not have indexer. So it’s not very much a writer, as it can not set value of existing index.

You probably look for NativeList.AsArray() or NativeList.AsDeferredJobArray(). And mark [NativeDisableParallelForRestriction] on the returned NativeArray.

But you need to be sure different job batch is not writing to the same index.

1 Like

Great marking NativeList with [NativeDisableParallelForRestriction] was enough.
Do I get benefits by exposing it as NativeArray ?

  1. It runs faster
  2. [NativeDisableParallelForRestriction] will completely disable safety checks. If you cast it to an array, it will still be able to gurantee thread safety
1 Like

But should I cast it outside the Execute() or I can do it inside and cast it to local variable ?

If I cast it outside and keep it as an additional member (I want to keep NativeList also all inside job struct) will it affect performance since struct will be bigger because of this additional fields ?

The last question when i do Nativelist.AsArray will this new array Length property change when NativeArray gets new items ?

See
NativeList.AsDeferredJobArray()

1 Like