Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Read NativeQueue inside a job

Discussion in 'Entity Component System' started by GilCat, Feb 3, 2019.

  1. GilCat

    GilCat

    Joined:
    Sep 21, 2013
    Posts:
    676
    I'm getting InvalidOperationException: The native container has been declared as [ReadOnly] in the job, but you are writing to it.
    This happens when i try to dequeue from the NativeQueue inside an job.
    Code (CSharp):
    1.      
    2.   struct MyJob : IJobParallelFor {
    3.     [ReadOnly]
    4.     public NativeQueue<int> MyNativeQueue;
    5.     public void Execute(int index) {
    6.       while (MyNativeQueue.TryDequeue(out var element)) {
    7.         // Do something with the element
    8.       }
    9.     }
    10.   }
    11.  
    Is this possible or am i missing something?

    Thanks
     
  2. dartriminis

    dartriminis

    Joined:
    Feb 3, 2017
    Posts:
    157
    TryDequeue is a write operation, since it also removes the element from the collection.
     
    GilCat likes this.
  3. GilCat

    GilCat

    Joined:
    Sep 21, 2013
    Posts:
    676
    Yes i know but if i removed the [ReadOnly] i can only use the concurrent version and that only allows me to "Enqueue".
    I will get an error
    InvalidOperationException: MyJob.NativeQueue is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing. Please use a more suitable container type.

    So i guess i can only read the the values of the NativeQueue in the main thread.
     
  4. xman7c7

    xman7c7

    Joined:
    Oct 28, 2016
    Posts:
    28
    use IJob instead of IJobParallelFor. If you need something to do inside IJobParallelFor you have to use concurrent version. Right now for NativeQueue with concurrent you can only use enqueue. Maybe in future we can dequeu
     
    GilCat likes this.
  5. Attatekjir

    Attatekjir

    Joined:
    Sep 17, 2018
    Posts:
    23
    You are not able to read from a NativeQueue in parallel.

    What you could do is schedule an IJob and in it dequeue the elements from the NativeQueue into a NativeArray or NativeList. After which you are able to read from the NativeArray in your IJobParallelFor.
     
    GilCat likes this.