Flickering background when updating img.pixels[] in another thread

Hello,

When I’m updating the pixels of an PImage in a different thread this somehow effects the background of my main (P3D) sketch (on both Mac and Window). Even when the image is not bound as a texture. Any idea?

PImage img;
boolean loading;

void setup() {
  size(1200, 1200, P3D);
  img = createImage(2048, 1024, RGB);
}

void draw() {
  background(0);

  if (!loading) {
    thread("loadFrame");
  }
}

void loadFrame() {
  loading=true;

  img.loadPixels();
  for (int i=0; i<img.width*img.height; i++) {
    img.pixels[i] = color(i%255, 255, 255);     ////  UPDATE: calling color() inside the thread was causing it.
  }
  img.updatePixels();

  loading=false;
}

Some glitches here & there are expected if we mutate pixels[] in a separate Thread at the same time another 1 displays it. :roll_eyes:

However, much worse than that is concurrently use any methods related to color under diff. threads! :fearful:

Main “Animation” Thread is invoking background() while the other Thread is invoking color()! :grimacing:

As a workaround, you can createGraphics() under the other Thread and invoke color() via that PGraphics. :bulb:

Or just don’t use color() at all. You can use bitshifting operations instead. :smile_cat:

Cool, thanks! The color() function was causing it.

bitshifting instead of using color() solves the issue:
img.pixels[i] = i%255 << 16 | 255 << 8 | 255;

note that I was not accessing pixels[] but img.pixels[].