Search Unity

Question Counter without unsafe code for IJobParralelFor

Discussion in 'C# Job System' started by DevDunk, Apr 28, 2023.

  1. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    5,043
    I am writing a multithreaded mesh slicer, which is becoming a nightmare since I cannot use lists and queues (even not as parralelWriter).
    Now it could work with an array, but I have to manually keep track of how many items in an array actually get filled.
    I thought of using some kind of counter, but found it very hard to implement this is multithreaded jobs. Most solutions I find end up using unsafe code, which I have to avoid.

    Does anyone have any suggestions on how to implement this?

    (my backup is making a small job after the processing that can read which values have changed and then count those, but that's not ideal)
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    5,890
    Hard to discuss the problem statement without seeing some code.

    One of the knot-breaking thoughts is to overcome the idea that you have to use atomic items such as a simple value of a counter.

    Instead, you could have an int array of the same size that the IJobParallelFor is processing. For every iteration, you write the count that it generates (possibly just 0 or 1) to the array. Once all these jobs are done, launch another "Sum" job that simply takes that array and creates the sum of all the ints in the array.

    This is tremendously fast (especially when bursted and most importantly: no branching inside the Execute method), even though it seems to go against regular programming tactics of not needlessly enumerating the same array twice.
     
    DevDunk likes this.
  3. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    5,043
    The idea with an array of the same sounds might just work out perfectly, I'll try it out!
    Thanks!
     
  4. vectorized-runner

    vectorized-runner

    Joined:
    Jan 22, 2018
    Posts:
    398