Is there a way to put the entire function signature with arguments into the thread call?

Hi,

Is there a way to put the entire function signature with arguments into the thread call? What would you add to the “requestData” call?

String time = "";

void setup() {
  size(100, 100);
}

void draw() {
  background(0);
  // Every 30 frames request new data
  if (frameCount % 30 == 0) {
    thread("requestData");
  }
  text(time, 10, 50);
}

// This happens as a separate thread and can take as long as it wants
void requestData() {
  JSONObject json = loadJSONObject("http://time.jsontest.com/");
  time = json.getString("time");
}

Unfortunately no! Processing functions thread() & method() can only invoke functions w/ signature void () that belong to PApplet.

Unless you create your own Thread subclass:
https://docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html

Just like we do w/ Processing callbacks setup(), draw(), mousePressed(), etc., we rely on “global” variables; both to “send” & “return” data.

BtW, your posted thread()'s example code keeps recreating a Thread @ 30 FPS.

Given we just need the same Thread code for the duration of the sketch, we can keep it alive via an infinite loop + delay():

String time = "";

void setup() {
  size(300, 100);

  fill(#FFFF00);
  textSize(050);
  textAlign(CENTER, CENTER);

  thread("jsonDataLoop");
}

void draw() {
  background(#0000FF);
  text(time, width >> 1, height >> 1);
}

void jsonDataLoop() {
  for (;; delay(50))
    time = loadJSONObject("http://Time.JSONTest.com").getString("time");
}

Notice that on this modified version we only invoke thread() once within setup().

2 Likes