Interlocked class vs NativeArray

Hi everyone!
Hope Unity team will read this and will do something about it. Native array elements can not be passed by ref argument in methods. Because of this it is not possible to use Interlocked class methods on the elements of NativeArray. In my case the array of integers (bit flags) represents the results of the IJobChunk job. The job checks a number of conditions for every entity in every chunk and set appropriate bits in the elements of the array of ints. On a rare occasion two chunk jobs need to modify the same element of array. I wanted to use Interlocked.Or for that but now I need to increase the array size to match chunks count and merge them back when the chunk job is done. This introduces a lot of overhead and unnecessary work to do.
Thanks!

The indexer intentionally doesn’t return refs to prevent invalid memory access eg when the NativeArray is destroyed and the ref is still in use.

You might use an extension like this eg to use it with Interlocked:

    public static ref T GetUnsafeRef<T>(this NativeArray<T> self, int index)
        where T : struct
    {
        return ref UnsafeUtility.ArrayElementAsRef<T>(self.GetUnsafePtr(), index);
    }
2 Likes