Simple
In this example, we create a Piscina instance that uses BroadcastChannel(Node v18+) to implement broadcast communication. The main thread sends a message, and other threads the receive message.
- Javascript
index.js
'use strict';
const { BroadcastChannel } = require('worker_threads');
const { resolve } = require('path');
const Piscina = require('piscina');
const piscina = new Piscina({
filename: resolve(__dirname, 'worker.js'),
atomics: 'disabled'
});
async function main () {
const bc = new BroadcastChannel('my_channel');
// start worker
Promise.all([
piscina.run('thread 1'),
piscina.run('thread 2')
]);
// post message in one second
setTimeout(() => {
bc.postMessage('Main thread message');
}, 1000);
}
main();
worker.js
'use strict';
const { BroadcastChannel } = require('worker_threads');
module.exports = async (thread) => {
const bc = new BroadcastChannel('my_channel');
bc.onmessage = (event) => {
console.log(thread + ' Received from:' + event.data);
};
await new Promise((resolve) => {
setTimeout(resolve, 2000);
});
};
You can also check out this example on github.