#Compile additive results in parallel. Better solution?

1 messages · Page 1 of 1 (latest)

fiery moss
#

I have a NativeArray<int> where the index represents a hashed spatial position. I need to compute how many elements are in each cells, so jobs will write to the same index simultaneously.

My current solution is to make the array the expected table size * JobsUtility.ThreadIndexCount and use JobsUtility.ThreadIndex to know where to write in the array from the job(threadindex * tableSize + index). Once the job is complete, compile all the results.

Is there better solution?

digital fox
#

System.Threading.Interlocked.Increment maybe?

fiery moss
#

I don't think I can make this play nicely with burst

fiery moss
# hexed silo it's supported by burst

My problem is passing the values from my nativearray by ref. That does not seem currently supported. I am reading about solutions with unsafe pointers, it might be doable

hexed silo
#

it is supported

fiery moss
#

How can I achieve it?

hexed silo
#

There's built in utility

#

Not sure what's it's name

fiery moss
#

Ok, built in util to do what?

hexed silo
#

but basically, all you need is GetUnsafePtr()[index]

#

that's what this util does

fiery moss
#

UnsafeUtility.ArrayElementAsRef?

hexed silo
#

public ref T GetRef(this NativeArray<T> arr, int index) { return ref arr.GetUnsafePtr()[index]; }

#

yeah

#

that one I think

#

either way

#

that's all the code you need

fiery moss
#

Awesome, thank you very much

hexed silo
#

just beware of crashes, because my code does not have any length checks 😅

keen marten
#

Question is, is Interlocked actually more performant than calculating per thread and merging?

#

My intuition tells me if number of cells is the larger number factor Interlocked wont collide as often on cache lines. If you have a lot of points on a few cells on the other hand it feels like the separate add structure per thread would be better off. 🤷