Eseguire lavoro pesante in un thread o in un processo figlio
Node.js esegue il tuo codice su un solo thread, quindi un calcolo lungo blocca ogni richiesta. NEWTHREAD(name, data) avvia workers/<name>.js in un thread worker e restituisce un Worker standard di Node.js: invialo messaggi con worker.postMessage(value), ricevi le risposte con worker.on('message', fn) e fermalo con worker.kill(). Il secondo argomento (data) viene consegnato al worker come dati iniziali. NEWFORK(name) ha la stessa forma ma avvia un processo figlio separato, isolato dal processo principale (un suo crash non coinvolge la tua app).
Dentro il file del worker, NEWTHREAD() senza argomenti restituisce l'handle del worker: worker.data contiene i dati iniziali, worker.message = fn riceve i messaggi e worker.postMessage(value) risponde. Passa un nome con il prefisso ~ per usare un file tramite il suo percorso invece di workers/<name>.js.
require('total5');
const worker = NEWTHREAD();
const start = worker.data.start;
worker.message = function(message) {
let total = start;
for (let i = 1; i <= message.to; i++)
total += i;
worker.postMessage({ total: total });
};exports.install = function() {
ROUTE('GET /sum/{to}/', sum);
};
var thread = NEWTHREAD('sum', { start: 1000 });
function sum($) {
var to = +$.params.to;
var timeout = setTimeout(() => $.invalid('timeout'), 4000);
thread.once('message', function(response) {
clearTimeout(timeout);
$.json(response);
});
thread.postMessage({ to: to });
}