Using a thread to fire off function, doesn't render text

edited October 12 in Questions about Code

I'm using a thread to fire an event every few seconds. When I call the function in setup, it works. When I call the function from the thread, it runs, as I can debug through, but nothing is printed to screen using rect/text.

final static int TIMER = 5 * 1000;  
static String msg; 
static boolean isEnabled = true; 
int left=0;
int f = 255;

void setup() {
  size(320, 240);
  fill(#FFFF00);
  textSize(32);
  textAlign(CENTER, CENTER);
  fireTimer();            // this one works
  thread("timer");  
}

void draw() {
   f = (f > 10) ? f-10 : 255;
  fill(f);
  rect(left, 10, 10, 10);
  left += 10;
  if (left > width) left = 0;
}

void fireTimer() {
    msg = nf(minute(), 2) + ":" + nf(second(), 2);
    println("Triggered @ " + msg);
    fill(0);
    rect(width/4, height/4, width/2, height/2);
    fill(255);
    text(msg, width/2, height/2);
}

void timer() {
 while (isEnabled) {
    delay(TIMER);
    fireTimer();
  }
}

Answers

  • Answer ✓

    edit post, highlight code, press ctrl-o to format.

    drawing things in trhreads is generally not a good idea - set a flag and check the flag, render the text in draw().

  • edited October 12

    Sure, just doesn't feel so good. Thanks for the quick reply... and the formatting help.

  • You can only update the display in the main event thread (Java thing) so the display commands are ignored from the secondary thread.

    The trick is to use the second thread to indicate when the mani thread should update the display. Like this.

    final static int TIMER = 5 * 1000;
    static String msg; 
    static boolean isEnabled = true; 
    boolean isReady = true;
    int left=0;
    int f = 255;
    
    void setup() {
      size(320, 240);
      fill(#FFFF00);
      textSize(32);
      textAlign(CENTER, CENTER);
      thread("timer");
    }
    
    void draw() { 
      f = (f > 10) ? f-10 : 255; 
      fill(f); 
      rect(left, 10, 10, 10); 
      left += 10; 
      if (left > width) left = 0;
      if(isReady){
        fireTimer();
        isReady = false;
      }
    }
    
    void fireTimer() { 
      msg = nf(minute(), 2) + ":" + nf(second(), 2); 
      println("Triggered @ " + msg); 
      fill(0); 
      rect(width/4, height/4, width/2, height/2); 
      fill(255); 
      text(msg, width/2, height/2);
    }
    
    void timer() { 
      while (isEnabled) { 
        delay(TIMER); 
        isReady = true;
      }
    }
    
  • Thanks everyone. Setting a flag now.

Sign In or Register to comment.