Feb 6, 2012

Trheading a function with parameters in Processing

In Processing if you want that a function is executed in a diferent thread, you have just to use the following command:

  thread("myFunc");       // this command creates a new thread and executes myFunc in that thread

  void myFunc(){ ..... }

  The restriction is that 'myFunc' must be void, with no parameters and it could not be declared in a subclass in the sketch (it must be a public function in the pApplet class).

With the following code you could thread a public function inside any class, with any number of parameters:

public void thread(final Metode metode, final Object... parametres) {                 // és el mateix que el thread de Processing, però amb paràmetres
  Thread later = new Thread() {  public void run() {  metode.run(parametres);  }  };  // i a més el Mètode pot pertanyer a qualsevol Clase

to use this alternative version of 'thread', you have to do the following:

 Metode resend = new Metode(myObject, "myFunc", byte.class, int.class);
 thread( resend, toSend, mill );
where 'myObject'  is an object of the cass that contains myFunc  (if the function is in in the same class were you declare 'resend' you can use 'this' instead of 'myObject'):
  class myClass{
    public void myFunc(byte toSend, int mill){ ..... }

  myClass myObject = new myClass();

you can find 'Metode' class in this post: Metode Class