thread-workers
v0.0.3
Published
A simple wrapper for threading in node
Downloads
3
Readme
Thread Workers
Thread workers is a simple, easy-to-use lib which allows you to run CPU-intensive tasks in threads, and communicate between these threads and the main thread.
run
Import run
from the package as follows:
import { run } from 'thread-workers';
Then, to run a task in a thread, call run
with a function.
const one = await run(() => 1);
Make sure that the function you passed in contains no reference to outside scopes. For example, this would not work:
const one = 1;
const two = await run(() => one + 1);
But this would:
const two = await run(() => {
const one = 1;
return one + 1;
})
spawn
Import spawn
from the package as follows:
import { spawn } from 'thread-workers';
Now, spawn
is a slightly lower-level implementation. It's best you use it when you want your threads to last long, and is made to communicate between the main thread and the spawned thread.
spawn
works by letting you receive messages between threads using events
. Take the following as an example:
const thrd = spawn<{
toLog: [ string ]
}, {}, void>(async comms => {
const [ msg ] = await comms.waitFor('toLog');
console.log(msg);
});
thrd.once('ready', () => {
thrd.send('toLog', 'Hello world!'); // Hello world!
});
Or sending messages back to the main thread:
const thrd = spawn<{}, {
helloMainThread: [ string ]
}, void>(async comms => {
comms.send('helloMainThread', 'How are you?');
});
thrd.on('helloMainThread', msg => {
console.log('The worker thread said the following:', msg);
})
If you want to get the return value
using spawn, you'll need to use the done
event.
which to use
For simpler things, like calculating something CPU-intensive, run
is usually a bit more convenient. Here's how to sum numbers with run
:
const sum = await run((comms, toSum: number[]) => {
return toSum.reduce((acc, cur) => acc + cur);
}, [ 1, 2, 3, 4 ]);
While here's how to sum numbers using spawn
:
const thrd = spawn(async (comms, toSum: number[]) => {
return toSum.reduce((acc, cur) => acc + cur);
}, [ 1, 2, 3, 4 ]);
const [ sum ] = await thrd.waitFor('done');