# Eseguire lavoro pesante in un thread o in un processo figlio

> Usa NEWTHREAD() per avviare un thread worker, inviargli messaggi e leggere le risposte senza bloccare il processo principale.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: it
Content-SHA256: 61028d15d5d94f1a4f9ca023acde970c80493ed0677c38e356bd68693277d9bb
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

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`.

```js workers/sum.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 });
};
```

```js controllers/sum.js
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 });
}
```
