Search code examples
haxenekohaxelib

haxelib run can't start new threads?


I'm getting an exception when trying to use the haxelib run command on my test Haxelib:

haxelib run haxelib-test

D:\HaxeToolkit\haxe\std/neko/vm/Thread.hx:54: characters 20-71 : Can't create thread from within a macro

Without threading everything works okay.

Haxe code:

import neko.vm.Thread;

class Main {
    static function main() {
        trace("starting");
        var commandsThread = Thread.create(read);
        trace("ending");
    }

    static function read() {
        trace("new thread");
    }
}

My haxelib.json looks like this:

{
    "name": "haxelib-test",
    "license": "MIT",
    "tags": [],
    "description": "",
    "version": "0.0.1",
    "classPath": "src/",
    "main": "Main"
}

Solution

  • From the Haxelib docs you linked:

    Libraries with either a run.n helper or a main class defined in haxelib.json, can be executed using haxelib run.

    Since you're providing a main class, Haxelib is trying to run your code in Haxe's built-in macro interpreter using the --interp argument.

    Haxe 3's macro interpreter did not support threading, hence the error. You can work around this by compiling a run.n file and packaging that with your library, so the script is executed in Neko VM:

    haxe -main Main -neko run.n
    

    Haxe 4 introduced threading support for its new macro interpreter called "Eval" in the preview.5 release. Starting with that version, you can use eval.vm.Thread. However, note that this would make your Haxelib's run command not work for people running older Haxe versions. So if you're going for maximum compatibility, stick to Neko for now.