You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Work has been started on workers in node.js (nodejs/node#20876). The idea looks great, and we should make sure our pthreads code works there too. The API (which presumably isn't final) looks more or less like web workers, so it shouldn't be too hard to make it work.
I had forgotten that someone had already filed a bug about this previously: #6332 In any case, we should make this work for node.js as well as browsers.
Experimenting with this, it is blocked on nodejs/node#25630 - looks like in node a blocking main does not send postMessages to workers (or perhaps blocks all logging from them).
You can postMessage from main to worker, no problem, but console.log() in a worker sends the string to the main thread, to print it on the worker's behalf.
The main thread won't process that string until control returns to the event loop and fixing that is not trivial.
Latest node may be enough, yeah. Last I tried it seemed possible, but getting logging working from a pthread (while the main is busy) was hard, so it was difficult to make progress. I have a wip branch here:
I may not have time for this myself in the near future. If someone has time to look at that that would be great, it might be a matter of finding some hack for debugging (like maybe printing to a file?), then fixing some minor issues.
I looked at this a little more now, there is some progress in the branch. Overall I keep hitting the many small differences between a Web Worker and a Node Worker.
For example the current blocker is that on the web we use importScripts to load the main x.js from the x.worker.js. Node doesn't have importScripts. The closest I can find is to load the code and do a global eval, but when doing that, require() is not defined, and we need that to be able to read files etc. Any ideas?
@kripken Maybe I’m misunderstanding, but what’s a “global eval” in that context? eval('require') should give the require function as long as the outer context already has it.
It's something like eval.call(null, '...'), which can add stuff to the global scope (and not just the current function scope if there is one), which we need to match importScripts. The emscripten code is here and here's an example of why it's needed:
functionsetup(){eval('function foo() {}');// normal evalconsole.log(typeoffoo);// okeval.call(null,'function baz() {}');// global evalconsole.log(typeofbaz);// ok}setup();console.log(typeoffoo);// bad!console.log(typeofbaz);// ok
Turns out in node a normal eval does see require, but a global one doesn't :( But it does work in V8 and SpiderMonkey...
In that case, maybe doing something like we do for the REPL in Node.js is a good approach? Basically, we copy/provide Node’s special per-module variables, require, module, exports, require, __dirname and __filename to the global object, and then run eval() on the script.
I think that’s something that makes sense when your goal is to have everything in the global scope, as it would be in a Web Worker?
The catch is that this picks one require function out of possibly many, namely the one for the main Worker script, but I think that that’s what you might want?
I think in nodejs module scope is different to global scope (I am not a nodejs programmer to be clear).
I got this working by assigning process, __filename etc like this in globalEval
And then just changing all of the variable definitions in worker.js to global variables, instead of using var. Not a particularly elegant solution, but it does work (tested on a fairly complicated threaded application).
A problem is that we want our builds to run on both the Web and Node.js. But it seems like in worker.js we need var threadInfoStruct = 0; on the Web but global.threadInfoStruct = 0; on Node?
If there's no other option we can force such builds to be either Web or Node but not both, but this is the first time we've run into such a situation, so it would be something we need to consider carefully.
@kripken A var inside a global eval does result in a global variable, both in Node.js and in the Web; so the main options for consistency between the Web and Node.js seem to be either a) grabbing the global object and then always setting properties on that, or b) wrapping most of the worker.js code itself in a global eval and using var declarations, e.g. along the lines of @cambeaney’s suggestion?
Oh thanks @addaleax, I missed the part about running worker.js itself in a global eval. Yes, that seems like it might help!
Meanwhile I am refactoring this code in #9569 which will remove some of those globals, and may remove almost all the ones we need to share between the files. After that lands I'll get back to this and see how things look.
I just had a quick look, and one other issue I ran into was that node.js workers don't support addEventListener. They have a bug open to add support: nodejs/node#26856.
@VirtualTim Node.js currently doesn’t support EventTarget for any built-in, and I wouldn’t count on that changing soon (unless you’re willing to put work into that yourself 🙂). The only thing we do support is .onmessage for MessagePort instances, for alignment with the web.
Ok, after merging in that PR there is good news and bad news. The good news is that it looks like a simple program can work! It creates 3 pthreads and they each do some work and print out their progress :)
The bad news is that it looks like a pthread exiting shuts down the whole node.js instance. Shutdown is done by throwing an exception, which on the web stays in the worker (it's logged to the console, but that's it), while in node it seems to halt the entire application,
a.out.js:154
throw ex;
^
Error [ERR_UNHANDLED_ERROR]: Unhandled error. (55)
at Worker.emit (events.js:198:17)
at Worker.[kOnErrorMessage] (internal/worker.js:176:10)
at Worker.[kOnMessage] (internal/worker.js:186:37)
at MessagePort.<anonymous> (internal/worker.js:118:57)
at MessagePort.emit (events.js:209:13)
at MessagePort.onmessage (internal/worker/io.js:70:8) {
context: 55
}
and the node.js process exits with code 1. This is a problem since threads should call pthread_exit(), and that method must throw (it's marked as noexit in C, so clang emits an unreachable at the end, which throws; we normally don't reach it and throw a JS exception, which is on line 154 there; removing that, it just prints that the unreachable is thrown). We should be able to handle pthreads exiting and new ones being started etc., so it's not immediately obvious to me what to do.
@kripken Would trying to call process.exit() in Node.js Workers an option (possibly guarded by a check for the presence of it)? It throws an un-catchable JS exception that terminates the Worker, so it should do exactly what you want.
Otherwise, listening to the 'error' event on the Worker instance should be the way to go…
Activity
dschuff commentedon May 22, 2018
I had forgotten that someone had already filed a bug about this previously: #6332 In any case, we should make this work for node.js as well as browsers.
kripken commentedon May 12, 2019
Experimenting with this, it is blocked on nodejs/node#25630 - looks like in node a blocking main does not send postMessages to workers (or perhaps blocks all logging from them).
bnoordhuis commentedon May 13, 2019
Just to confirm: that's what happens.
You can postMessage from main to worker, no problem, but
console.log()in a worker sends the string to the main thread, to print it on the worker's behalf.The main thread won't process that string until control returns to the event loop and fixing that is not trivial.
kripken commentedon May 13, 2019
I see, thanks @bnoordhuis!
Maybe we can work around it by using stdout/stderr directly? Or would that not work either?
bnoordhuis commentedon May 13, 2019
No, unfortunately. All stdio is mediated in Node's workers.
kripken commentedon May 14, 2019
I see, thanks. Ok, sadly I think that means we can't use node workers in a simple way here.
walkingeyerobot commentedon Aug 26, 2019
I believe bleeding edge Node should have all the support necessary.
kripken commentedon Aug 26, 2019
Latest node may be enough, yeah. Last I tried it seemed possible, but getting logging working from a pthread (while the main is busy) was hard, so it was difficult to make progress. I have a wip branch here:
https://github.com/emscripten-core/emscripten/tree/node-pthreads
I may not have time for this myself in the near future. If someone has time to look at that that would be great, it might be a matter of finding some hack for debugging (like maybe printing to a file?), then fixing some minor issues.
kripken commentedon Sep 24, 2019
I looked at this a little more now, there is some progress in the branch. Overall I keep hitting the many small differences between a Web Worker and a Node Worker.
For example the current blocker is that on the web we use
importScriptsto load the mainx.jsfrom thex.worker.js. Node doesn't haveimportScripts. The closest I can find is to load the code and do a global eval, but when doing that,require()is not defined, and we need that to be able to read files etc. Any ideas?addaleax commentedon Sep 24, 2019
@kripken Maybe I’m misunderstanding, but what’s a “global eval” in that context?
eval('require')should give the require function as long as the outer context already has it.kripken commentedon Sep 24, 2019
@addaleax
It's something like
eval.call(null, '...'), which can add stuff to the global scope (and not just the current function scope if there is one), which we need to matchimportScripts. The emscripten code is here and here's an example of why it's needed:Turns out in node a normal eval does see
require, but a global one doesn't :( But it does work in V8 and SpiderMonkey...Maybe there's a better way I'm missing?
addaleax commentedon Sep 24, 2019
Okay, I see – thanks for the explanation.
In that case, maybe doing something like we do for the REPL in Node.js is a good approach? Basically, we copy/provide Node’s special per-module variables,
require,module,exports,require,__dirnameand__filenameto the global object, and then runeval()on the script.I think that’s something that makes sense when your goal is to have everything in the global scope, as it would be in a Web Worker?
kripken commentedon Sep 25, 2019
Interesting, thanks - so there's a way I can copy
requireto the global scope, and global eval would see it? How would I do that copy?addaleax commentedon Sep 25, 2019
So, just to avoid any confusion, I’m basically talking about doing this inside the Worker:
The catch is that this picks one
requirefunction out of possibly many, namely the one for the main Worker script, but I think that that’s what you might want?4 remaining items
cambeaney commentedon Sep 30, 2019
I think in nodejs module scope is different to global scope (I am not a nodejs programmer to be clear).
I got this working by assigning process, __filename etc like this in globalEval
And then just changing all of the variable definitions in worker.js to global variables, instead of using var. Not a particularly elegant solution, but it does work (tested on a fairly complicated threaded application).
kripken commentedon Oct 1, 2019
@addaleax @cambeaney
A problem is that we want our builds to run on both the Web and Node.js. But it seems like in worker.js we need
var threadInfoStruct = 0;on the Web butglobal.threadInfoStruct = 0;on Node?If there's no other option we can force such builds to be either Web or Node but not both, but this is the first time we've run into such a situation, so it would be something we need to consider carefully.
addaleax commentedon Oct 1, 2019
@kripken A
varinside a global eval does result in a global variable, both in Node.js and in the Web; so the main options for consistency between the Web and Node.js seem to be either a) grabbing the global object and then always setting properties on that, or b) wrapping most of the worker.js code itself in a global eval and usingvardeclarations, e.g. along the lines of @cambeaney’s suggestion?kripken commentedon Oct 3, 2019
Oh thanks @addaleax, I missed the part about running
worker.jsitself in a global eval. Yes, that seems like it might help!Meanwhile I am refactoring this code in #9569 which will remove some of those globals, and may remove almost all the ones we need to share between the files. After that lands I'll get back to this and see how things look.
Fix pthreads with closure compiler (#9569)
VirtualTim commentedon Oct 18, 2019
I just had a quick look, and one other issue I ran into was that node.js workers don't support
addEventListener. They have a bug open to add support: nodejs/node#26856.addaleax commentedon Oct 18, 2019
@VirtualTim Node.js currently doesn’t support
EventTargetfor any built-in, and I wouldn’t count on that changing soon (unless you’re willing to put work into that yourself 🙂). The only thing we do support is.onmessageforMessagePortinstances, for alignment with the web.kripken commentedon Oct 24, 2019
Ok, after merging in that PR there is good news and bad news. The good news is that it looks like a simple program can work! It creates 3 pthreads and they each do some work and print out their progress :)
The bad news is that it looks like a pthread exiting shuts down the whole node.js instance. Shutdown is done by throwing an exception, which on the web stays in the worker (it's logged to the console, but that's it), while in node it seems to halt the entire application,
and the node.js process exits with code 1. This is a problem since threads should call
pthread_exit(), and that method must throw (it's marked as noexit in C, so clang emits an unreachable at the end, which throws; we normally don't reach it and throw a JS exception, which is on line 154 there; removing that, it just prints that the unreachable is thrown). We should be able to handle pthreads exiting and new ones being started etc., so it's not immediately obvious to me what to do.addaleax commentedon Oct 25, 2019
@kripken Would trying to call
process.exit()in Node.js Workers an option (possibly guarded by a check for the presence of it)? It throws an un-catchable JS exception that terminates the Worker, so it should do exactly what you want.Otherwise, listening to the
'error'event on the Worker instance should be the way to go…kripken commentedon Oct 30, 2019
Excellent, thanks @addaleax! That works :)
kripken commentedon Oct 31, 2019
PR is finally up, with a first passing test! #9745 Thanks again for all the help here :)
Basic pthreads support for Node.js Workers (#9745)
Fix pthreads with closure compiler (emscripten-core#9569)
Basic pthreads support for Node.js Workers (emscripten-core#9745)