Skip to content

Instantly share code, notes, and snippets.

@SimonRichardson
Last active December 16, 2015 22:39
Show Gist options
  • Select an option

  • Save SimonRichardson/5508266 to your computer and use it in GitHub Desktop.

Select an option

Save SimonRichardson/5508266 to your computer and use it in GitHub Desktop.
This is a basic idea (proof of concept) to get isolates working in haxe by default. This should make it easier to make working with WebWorkers easier. Obviously you could use Actors to do the event managing behind the scenes and you would never know that you're using web workers (in theory)
package ;
@:remove
@:autoBuild(IsolateTypes.build())
extern interface Isolate {}
class Isolates {
private static var _isolates : Array<Class<Isolate>> = [];
private var _type : Class<Isolate>;
public function new(type : Class<Isolate>) {
_type = type;
}
public function start() : Void {
// TODO (Simon) : Wire up sending and receiving messages between isolates (via ActorSystem?)
var code = '
importScripts("name of current js file");
Main.main(${Type.getClassName(_type)});
';
var blob = new Blob([code], {
type: 'text/javascript'
});
var URL = untyped __js__('window.URL || window.webkitURL || window.mozURL || window.msURL || window.oURL');
_url = URL.createObjectURL(blob);
}
public static function add(isolate : Class<Isolate>) : Void {
_isolates.push(isolate);
}
public static function start(possible : String, fallback : Class<Isolate>) : Bool {
var isFallbackAvailable = false;
for (i in _isolates) {
if (Type.getClassName(i) == possible) {
Reflect.createInstance(i, []);
return true;
} else if (i == fallback) {
isFallbackAvailable = true;
}
}
if (isFallbackAvailable) {
Reflect.createInstance(fallback, []);
return true;
}
return false;
}
}
class IsolateTypes {
#if macro
public static function build() {
// TODO (Simon) : Auto wire up isolates to generate the correct registration when calling main.
}
#end
}
class Worker implements Isolate {
public function new() {
}
public function receive(value : AnyRef) : Void {
trace('Hello world!'); // Hello world!
}
// TODO (Simon) : This should automatically filled in by the macro
public static function __init__() : Void {
Isolates.add(Worker);
}
}
@:expose('Main')
class Main implements Isolate {
public function new() {
var isolate = new Isolate(Worker);
isolate.start();
isolate.send('Hello world!');
}
// TODO (Simon) : This should automatically filled in by the macro
public static function __init__() : Void {
Isolates.add(Main);
}
public static function main(possible : String) {
if(!Isolates.start(possible, Main)) {
throw 'Can not start $possible';
}
}
}
@SimonRichardson
Copy link
Copy Markdown
Author

Note: above is proof of concept and doesn't even run or compile, it's just here as an idea!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment