Can I terminate IJobParallelFor early when one of the loop meets a criteria?

I would like to make a job that loops through data in NativeArray to find an index that meets a criteria for example. (searching with only one correct result, searching for any items, etc)

In a normal loop I would do a linear search and return immediately when I found what I want. By using IJobParallelFor can I force all other work to stop when one of them found the answer and finished writing the answer out? This way .Complete would not have to wait until all other parallelized job to finish doing nothing useful.

4 Likes

Also interested in this

Edit:
I used this once when I compared speed of threads vs jobs in a pixel collision. I had a had a hacky solution for threads and I guess with the remove parallel write flag could also create one for jobs. At the time jobs where way slower than threads. I would like to get back to this and see how burst and the added functionality affect the job performance Vs threads.

+1 Any news on this?

old post but since it was uped, here is what I can think of without testing :

Use a static bool in the job structure set it when answer is found and test it to exit early from every thread.

If using static variable is not possible use a nativearray of 1 element with all safety guard disabled to do the same thing. we don’t car about the race condition in this case at worst we are reading the value one iteration “late”.

@WAYNGames that wouldn’t stop the job from running. And it wouldn’t stop the thread either. Returning out of the execute only skips the call of that method that one time on that thread. By setting a bool value, all threads will still check against that value for all remaining iterations. So at best you’re speeding up your job completion by making it do less work. That being said, if the execute method isn’t that intensive and your problem is that you’re executing many times, you’ll actually slow down your job because the execute method needs to check this Boolean each time it’s called in addition to all the work you were going to do anyway.

1 Like