Program in a Program?

Guess I got lucky with simple sketches.

I’m not an expert on multithreading, but would this naive code make it thread safe?

For this to fully work, there should be a way to synchronise all the animation threads across all the PApplet instances.

PWindow[] win;

public void settings() {
  size(600, 600);
}

void setup() { 
  win = new PWindow[4];
  for (int i = 0; i < win.length; i++)
  {
    win[i] = new PWindow((i/2)*300, (i%2)*300);
  }
  surface.setLocation(20, 20);
}

void draw() {
  background(0);
  for (int i = 0; i < win.length; i++)
  {
    synchronized(win[i].g)
    {
      image(win[i].get(), win[i].winPos.x, win[i].winPos.y);
    }
  }
}

void mousePressed() {
  for (PWindow window : win)
  {
    if (mouseOver(window.winPos.x, window.winPos.y, window.width, window.height))
    {
      window.mouseX = (int)(mouseX-window.winPos.x);
      window.mouseY = (int)(mouseY - window.winPos.y);
      window.mousePressed();
    }
  }
} 

boolean mouseOver(float x, float y, float w, float h)
{
  return mouseX >= x && mouseX <= x + w && mouseY >= y && mouseY <= y + h;
}

class PWindow extends PApplet {
  PVector winPos;
  PWindow(int x, int y) {
    super();
    winPos = new PVector(x, y);
    PApplet.runSketch(new String[] {this.getClass().getSimpleName()}, this);
  }

  int h = (int) random(255);
  PVector position;

  void settings() {
    size(300, 300);
  }

  void setup() {
    colorMode(HSB);
    position = new PVector(random(width), random(height));
    surface.setVisible(false);
  }

  void draw() {
    background(color(h++, 255, 255));
    ellipse(position.x, position.y, 50, 50);
    h=h%255;
    fill(0);
    rect(20, 8, textWidth(frameRate+""), 20); 
    fill(255);
    text(frameRate, 20, 20);
  }

  void mousePressed() {
    println(mousePressed);
    position.x = mouseX;
    position.y = mouseY;

  }
}

The mousePressed() implementation, while working in this example, is flawed. Maybe I shouldn’t be posting this, or somebody might run off with this code and try to attempt to use it in a real scenario :stuck_out_tongue: