Search code examples
asynchronoushaxe

How to not wait a function until it ends?


I have two functions:

function f1(a:String) {
    // long processes with a...
}

function f2() {
    f1("Hey");
    ...
}

What I want is:

when I call f1 from f2, I don't want to make f2 blocked. Neither I don't want, at some point in code, for f1's finishing (like joining threads)

I just want to call it and forget. It runs itself and finishes itself.

How can I manage this in Haxe? Thanks!


Solution

  • With Haxe < 4, this is a bit cumbersome. It works the same as with Haxe 4, but there isn't one cross-platform Thread type, making everything a little harder (cpp.vm.Thread, neko.vm.Thread etc).

    With Haxe 4 - even in its current release candidate state, you would achieve this with sys.thread.Thread. Every time you want to create a thread to execute your function, simply call Thread.create. One thing to notice is that this function takes a function with no argument that returns nothing. If your function takes one or more arguments, you can call its bind method as explained here : https://haxe.org/manual/lf-function-bindings.html .

    Long story short :

    import sys.thread.Thread;
    
    function f2() {
        var f1thread = Thread.create(f1.bind("Hey")); // runs instantly
    }
    

    Needless to say, you should check that the platform you are compiling for has threads.