Search Unity

NativeStream.Reader's Peek vs. Read

Discussion in 'Entity Component System' started by LuckyWonton, Jul 24, 2021.

  1. LuckyWonton

    LuckyWonton

    Joined:
    Feb 28, 2014
    Posts:
    19
    Can someone please explain the difference between these two methods?

    What I am trying to do is read the same data twice in a parallel process to avoid having to create a managed array.

    Code (csharp):
    1.             /// <summary>
    2.             /// Read data.
    3.             /// </summary>
    4.             /// <typeparam name="T">The type of value.</typeparam>
    5.             /// <returns>Reference to data.</returns>
    6.             [BurstCompatible(GenericTypeArguments = new[] { typeof(int) })]
    7.             public ref T Read<T>() where T : struct
    8.             {
    9.                 int size = UnsafeUtility.SizeOf<T>();
    10.                 return ref UnsafeUtility.AsRef<T>(ReadUnsafePtr(size));
    11.             }
    12.  
    13.             /// <summary>
    14.             /// Peek into data.
    15.             /// </summary>
    16.             /// <typeparam name="T">The type of value.</typeparam>
    17.             /// <returns>Reference to data.</returns>
    18.             [BurstCompatible(GenericTypeArguments = new[] { typeof(int) })]
    19.             public ref T Peek<T>() where T : struct
    20.             {
    21.                 int size = UnsafeUtility.SizeOf<T>();
    22.  
    23.                 byte* ptr = m_CurrentPtr;
    24.                 if (ptr + size > m_CurrentBlockEnd)
    25.                 {
    26.                     ptr = m_CurrentBlock->Next->Data;
    27.                 }
    28.  
    29.                 return ref UnsafeUtility.AsRef<T>(ptr);
    30.             }
    31.  
     
  2. Lorin_Atzberger

    Lorin_Atzberger

    Joined:
    Dec 11, 2013
    Posts:
    119
    You're unlikely to be able to do that with a NativeStream. Read advances the reading location (so the next read will read the next value). Peek just returns the data at the current reading location without advancing the location. If you want to read the same data in parallel I'd suggest using something like NativeArray or even the NativeList. The thing is that with multiple threads you're not guaranteed any kind of order of execution (other than job dependencies ofc).

    PS.: it might sound like you could read from one thread and peek from another but what can (and will) end up happening is that you're going to have multiple reads in a row, or multiple peeks in a row which.