How to pass arguments to a thread?

Hi there!

This is my code at the moment:

Thread.create( my_function );

I would like to pass some parameters upon creating the thread. However Thread.create only accepts an input of

() -> Void

so it seems I cannot pass any values to the thread. But I need something like this instead:

( a : MyClass ) -> Void

Or even any values.


Solutions (?)

  • Must I override the Thread.create field/method in a custom Thread class?
  • Do I need Thread.sendMessage and .readMessage for that?
  • Also this won’t work obivously:
Thread.create( my_function( a, b ) );

Let me know what you think.
Thank you.

	var mystr = "Hello";
	var myfunc = () -> { trace(mystr); }

	Thread.runWithEventLoop( myfunc );

Alternatively:

Thread.create(my_function.bind(a,b))
1 Like

That will not work because bind requires function taking array as an argument, while callback is of (Void)->Void type

Main.hx:: characters 2-13 : Too many callback arguments

Hi, thank you for your ideas!!

So in my case it seems the .bind() thing works with both the class method as well as with a local arrow function:

class Threads {
        static function main() {

                // uses method
                Thread.create( threadAcceptingArguments.bind("hi!") );

                Sys.sleep( 0.5 );

                // uses local arrow function
                var j = ( n:Int ) -> { trace( 'n=$n' ); };
                Thread.create( j.bind(10901) );

                Sys.sleep( 0.5 );
        }

        static function threadAcceptingArguments( string:String ) {
                trace( string );
        }
}

Output:

src/Threads.hx:5: hi!
src/Threads.hx:10: n=10901

I think this is still impressive that Thread.create( job:()->Void ) does accept “bind arguments” for job… I heard of bindings before, but now I’m glad they exist I guess.


edit: Maybe I should also say I only tried this with HashLink (!), maybe it won’t work on all platforms the same way (?)

Bind just creates closures around functions, i.e. it just does what you suggested but with simpler syntax.

Perhaps bind expects an array on a specific platform?

It was my mistake; I called bind on function without arguments, glad it works.

1 Like