# Run heavy work in a thread or a child process

> Use NEWTHREAD() to start a worker thread, send it messages and read the replies, without blocking the main process.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: en
Content-SHA256: 6be8eed8f5c6fc8d1a9a88a066519dbcd1b8884933677a534fc44d7c4d95f0d1
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

Node.js runs your code on one thread, so a long calculation blocks every request. `NEWTHREAD(name, data)` starts `workers/<name>.js` in a worker thread and returns a standard Node.js `Worker`: send it messages with `worker.postMessage(value)`, receive replies with `worker.on('message', fn)`, and stop it with `worker.kill()`. The second argument (`data`) is handed to the worker as its starting data. `NEWFORK(name)` has the same shape but starts a separate child process, which is isolated from the main process (a crash in it does not affect your app).

Inside the worker file, `NEWTHREAD()` without arguments returns the worker handle: `worker.data` holds the starting data, `worker.message = fn` receives messages and `worker.postMessage(value)` answers. Pass a name prefixed with `~` to use a file by path instead of `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 });
}
```
