How can I use Thread() with functions that has inputs

Hi, I had to run some functions asynchronously and I found a function called “Thread()”.
I’ve been using it easily with functions that have no inputs like…

void Something(){
}

thread("Something");

But I got a problem when it comes to functions with inputs.

void SomethingWithInput(int input){
}

something like this.

How can I use Thread function correctly in this kind of situation? Or maybe another method that I can run it asynchronously.

Thanks.

1 Like

You can’t, b/c its signature is parameterless & void. :no_entry:

Instead, you can create a class which extends Thread: :thread:
Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html

/**
 * Threaded Method (v1.0.1)
 * GoToLoop (2019/Jan/)
 *
 * https://Discourse.Processing.org/t/
 * how-can-i-use-thread-with-functions-that-has-inputs/12964/2
 */

void setup() {
  noLoop();
}

void draw() {
  background((color) random(#000000));
}

void mousePressed() {
  new ThreadedMethodWithIntParameter((int) random(100));
}

class ThreadedMethodWithIntParameter extends Thread {
  final int input;

  ThreadedMethodWithIntParameter(final int inp) {
    input = inp;
    start();
  }

  @Override void run() {
    println(input);
  }
}
3 Likes

I really thank you for your answer. Now I know how to deal with it. But I’m actually using a function with recursive call and I still don’t get it when it comes to this kind of function.

void QuickSort(int left, int right) {
 if (left <= right) {
 int pivot = Partition(left, right);
 QuickSort(left, pivot - 1);
 QuickSort(pivot + 1, right);
 }
 }
 
 int Partition(int left, int right) {
 int pivot = arr[left];
 int low = left + 1;
 int high = right;
 
 while (low <= high) {
 while (pivot >= arr[low] && low <= right) {
 low++;
 }
 while (pivot <= arr[high] && high >= (left+1)) {
 high--;
 }
 if (low <= high) {
 swap(low, high);
 }
 }
 swap(left, high);
 
 return high;
 }

(Quick sort function)

How can I use Thread for a function with recursive calls? Thanks a lot :slight_smile:

1 Like

I just simply solved it by using another void function

void QuickSortThread(){
   QuickSort(0,n); 
}

I guess it’s not the best way because the inputs cannot be not freely adjusted in this situation

1 Like

If you still want to have parameters, you can make something kind of like this:

int thing1;
int thing2;

void setup() {
    thing1 = 5;
    thing2 = 10;
    thread("thing");
}

void loop() {

}

void thing() {
    println(thing1);
    println(thing2);
}

You might need a 2D array for recursive sorting.

1 Like