Search Unity

Interlocked class vs NativeArray

Discussion in 'Entity Component System' started by palex-nx, Sep 10, 2021.

  1. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    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<int>. 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!
     
  2. julian-moschuering

    julian-moschuering

    Joined:
    Apr 15, 2014
    Posts:
    529
    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:
    Code (CSharp):
    1.     public static ref T GetUnsafeRef<T>(this NativeArray<T> self, int index)
    2.         where T : struct
    3.     {
    4.         return ref UnsafeUtility.ArrayElementAsRef<T>(self.GetUnsafePtr(), index);
    5.     }
    6.  
     
    apkdev and palex-nx like this.