Search Unity

Having trouble understanding this particular IJobChunk example

Discussion in 'Entity Component System' started by PhilSA, Jun 6, 2019.

  1. PhilSA

    PhilSA

    Joined:
    Jul 11, 2013
    Posts:
    1,926
    https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/UnityPhysicsExamples/Assets/Demos/6. Use Cases/CharacterController/Scripts/CharacterControllerBehaviour.cs

    I've been looking at the "CharacterControllerJob" here for a while and there's something I don't understand in there: This job takes a NativeArray of "CastHits", which stores all hits from physics queries up to a certain maximum... but how can this work in parallel?
    1. If this IJobChunk runs on 4 separate threads in parallel, and each thread tries to store cast hits in that array at the same time, won't they all interfere with each-other?
    2. Shouldn't we at least use "chunkIndex" to know where to write in our CastHits array? (make the array capacity be "maxNbHits * nbChunks", and then use "chunkIndex * maxNbHits" to find the start index of where you can write.... and then pass only that writeable NativeSlice to the hits collector, not the full NativeArray)
    3. Does IJobChunk make a copy of all of its inputs for each parallel job it starts?
    4. Am I correct in assuming that IJobChunk starts one job per chunk, all in parallel?
     
    Last edited: Jun 6, 2019
  2. JooleanLogic

    JooleanLogic

    Joined:
    Mar 1, 2018
    Posts:
    447
    My understanding is yes on 1, 3, and 4, with the fine print on 3 that only the job struct data would be copied, not the NativeArray data.
    For 2, normally you could use a chunk/entity index or thread index strategy but CastHits has an incrementing writer and the array is only 128 in size so those strategies don't make sense to me.

    Having said that, I have no idea how they're thread protecting that CastHits array.
    I followed that callstack all the way to the bottom and couldn't find anything that thread modifies the array write index. The CastHits array is passed into a Collector and the collector just sequentially adds the ColliderCastHit objects to it via a callback from the collision implementation.
    Presumably that would result in multiple threads writing to CastHits all starting from index 0 but that's obviously not the case.
    Maybe it's an implementation pattern or perhaps it's very obvious and I missed it. Probably something right at the top of the callstack lol.
    I would be curious to know myself as well.
     
    PhilSA likes this.
  3. dadude123

    dadude123

    Joined:
    Feb 26, 2014
    Posts:
    789