How to make Processing hang without eating CPU?

I am making a project that relies on the thread("..."); function extensively, and I want to find a way to make one of these threads to stop in the middle of the code without eating CPU.

The thing I am currently using is this:

void lag(float time){
int millis=millis();
while(millis()<millis+time/1000){float wow=floor(sin(0));}
}

This makes me able to run function lag(5); and that will make it wait 5 seconds, however this also eats a lot of CPU while it waits.

Or I can spam loadStrings("https://www.google.com"); a couple of times, which does not eat CPU, but is too unpredictable.

Is there a function that will work the same as my lag() function, but does not actually consume CPU?

Tagged:

Answers

  • For future readers, it should be mentioned that this is a perfect use for delay -- and almost every other use for delay is terrible!

    The delay() function should only be used for pausing scripts (i.e. a script that needs to pause a few seconds before attempting a download, or a sketch that needs to wait a few milliseconds before reading from the serial port.)

  • One very common use of delay() is when you create separate threads with infinite tight loops. Without delay() such a thread can hog the CPU making the sketch unresponsive.

    This sketch has two infinite loops each inside there own thread.

    int a = 10;
    float x, y, cx, cy, rx, ry;
    float ang = 0;
    
    void setup() {
      size(500, 200);
      textSize(40);
      cx = width/2;
      cy = height/2;
      rx = 0.9 * cx;
      ry = 0.9 * cy;
      thread("updateBallPos");
    }
    
    void draw() {
      background(0);
      fill(255);
      if (frameCount == 60) {
        thread("displayA");
      }
      text(a, cx - 20, cy + 20);
      fill(0, 255, 0);
      ellipse(x, y, 10, 10);
    }
    
    // This happens as a separate thread and can use delay freely
    void displayA() {
      while (true) {
        while (a > 0) {
          a--;
          delay(500);
        }
        delay(10000); // 10 seconds
        a = 11;
      }
    }
    
    // Infinite tight loop needs to allow other threads some CPU time
    void updateBallPos() {
      while (true) {
        ang += 0.03;
        x = cx + rx * cos(ang);
        y = cy + ry * sin(ang);
        delay(20);
      }
    }
    
Sign In or Register to comment.