Counter inside ScheduleParallel

Is there a way to keep a counter inside SchefuleParallel lambda

eg

int counter = 0
Entitie.ForEach(()=>
{
if( someCondition ) counter++;
}).ScheduleParrllel();

You can write your own simple nativecontainer using a lock but it’s not ideal and there are a lot of easy hacks you can do.

Such as if you simply did NativeQueue.ParallelWriter.Enqueue(byte) for your count tracker, then the Length of the queue is your counter. (I wouldn’t do this if I was counting to 10,000+s, there are alternatives)

Do you ever just spawn counter entities ? and query EntityCalculateCount(()

At lower entity counts (couple thousand) running this on a single thread (using .Run) will be faster.
I’ve ran into this a couple of times and found out the hard way that i was too obsessed with parallel scheduling.
Burst makes things freakishly fast, this is one of the examples where single thread simply stumps multithreading.

2 Likes

Check out the NativePerJobThreadIntPtr struct in this repo:

https://github.com/jacksondunstan/NativeCollections#nativeperjobthreadintptr-and-nativeperjobthreadlongptr

More about how this is implemented:

1 Like