Thread issue with while (true)

when I run a while (true) inside a thread
It only works if the condition play = 1 is met in the beginning.

but if play = 0 in the beginning, in the future of the program when play == 1 what is inside while is not running, I thought it should be executed since while (true) is waiting for instructions.

How do I make while (true) work at any time and not just in the beginning.

//variable init
play=0

void setup(){
 thread("holo");
}

void holo(){
  while(true){
    if (play==1){
      //...//it does not run because play 0 was initialized with 0
 //but it does not run in the future when play = 1;
    }
  }
}
1 Like

Use delay() for functions continuously running in another thread():
Processing.org/reference/delay_.html
Processing.org/reference/thread_.html

int play;
color c;

void setup() {
  size(200, 150);
  frameRate(4);
  thread("holo");
}

void draw() {
  play = round(random(1));
  background(c);
  getSurface().setTitle("Frames: " + frameCount);
}

void holo() {
  while (true) {
    if (play == 1)  c = (color) random(#000000);
    delay(1);
  }
}

Alternatively, declare the conditional variable as volatile:

volatile int play;
color c;

void setup() {
  size(200, 150);
  frameRate(4);
  thread("holo");
}

void draw() {
  play = round(random(1));
  background(c);
  getSurface().setTitle("Frames: " + frameCount);
}

void holo() {
  while (true) {
    if (play == 1)  c = (color) random(#000000);
    //delay(1);
  }
}
3 Likes