Need help with Jobs. Simple task for counting pixels.

Hello all !

I need to implement simple Job solution to count white pixels in the buffer.
But surprisingly it doesn’t seem to work – “sky_pixels++” results incorrect values.
How to fix it ?

public struct                   job_counter_t          : IJobParallelFor{
        public static Color32[]     buffer;
        public static uint          sky_pixels;
        public void                 Execute                             ( int i ){
            Color32     c           = buffer[i];
            if( c.r==255 && c.g==255 && c.b==255 ){
                sky_pixels          ++;
            }
        }
 }

I haven’t used the job system, but I would be really surprised if static variables are the way to go. Put it this way: the job system is multithreaded, and you now have multiple threads trying to read, increment, and write the same variable at the same time. That’s the classic pain point of multithreading that doesn’t work without synchronization.

This thread might help inspire you: [Job System] output scalar value from job

The increment of the static variable is one machine code instruction. Why need sync for this?

The ‘++’ operator is not an atomic operation.

https://stackoverflow.com/questions/17872057/is-operation-atomic-in-c
https://stackoverflow.com/questions/4628243/is-the-operator-thread-safe