- Home /
IJobParralelFor giving me random result.
Hello,
I have an array of boolean and I want to count elements that are true in this array. Since it's a big array, I wanted to use the Job System to optimize the process (and because I want to get familiar with this system to use it later).
First, I would like ot know if it is possible to do so with the IJobParallelFor struct and if it is relevant in the scenario where I can have a couple of frame to count the elements.
Then, my problem is that, everytime I try, it returns me a random lower number than the real number of true elements. After little debugging I found that the in the IJobParallelFor, the script counts the right number of element, so I guess that there is a problem when i get the value for the job but I can't see where.
I use the first element of a 'NativeArray' of size 1 to store the count, because I understood it can't be done with a simple integer (correct me if I am wrong).
Tell me what am I doing wrong!
//Job struct to count the number of true element in the data array
struct CountJob : IJobParallelFor
{
[ReadOnly]
public NativeArray<bool> data; //Array of boolean with random true/false elements
[NativeDisableParallelForRestriction]
public NativeArray<int> result; //Int array of size 1 to count the number of 'true' in data
public void Execute(int i)
{
//Everytime there's a true, the result should be incremented
if (data[i])
{
result[0] += 1;
Debug.Log("+1"); //Debug message which is called the expected amount of time
}
}
}
private void Start()
{
int debugCount = 0;
//Random false/true array initialization
bool[] debugData = new bool[4096];
for (int i = 0; i < debugData.Length; i++)
{
if (Random.value > 0.95f)
{
debugData[i] = true;
debugCount++;
}
else
debugData[i] = false;
}
//Prints the real number of true elements
Debug.Log("For-loop count : " + debugCount);
//NativeArray of the boolean array
NativeArray<bool> nativeData = new NativeArray<bool>(debugData, Allocator.Persistent);
//NativeArray of size 1 to store the count number
NativeArray<int> count = new NativeArray<int>(1, Allocator.Persistent);
count[0] = 0;
//We start the job
CountJob countJob = new CountJob() { data = nativeData, result = count };
JobHandle countHandle = countJob.Schedule(nativeData.Length, 64);
countHandle.Complete();
Debug.Log("Job system count : " + count[0]); //Prints a randomly lower value than the expected one
nativeData.Dispose();
count.Dispose();
}
I hope I am being clear, thanks
(First time posting here, tell me if something is wrong)
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
IJobParallelForTransform is not Multi threaded? 1 Answer