-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathworker_threads.js
More file actions
53 lines (43 loc) · 1.48 KB
/
Copy pathworker_threads.js
File metadata and controls
53 lines (43 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { URL } from 'url';
import { Worker, isMainThread, workerData } from 'worker_threads';
import Channel from '../dist/esm/worker_threads.js';
const filename = new URL('', import.meta.url).pathname;
const ch = new Channel('test', {
shutdownWorker: false
});
if (isMainThread) {
const bus = await ch.registerPromise([
new Worker(filename, { workerData: { id: 'worker #1' } }),
new Worker(filename, { workerData: { id: 'worker #2' } }),
new Worker(filename, { workerData: { id: 'worker #3' } })
]);
bus.listen('onCustomEvent', (msg) =>
msg && console.log('Received from worker thread:', msg));
bus.listen('shutdownWorker', (shutdownWorker) => {
if (!shutdownWorker) {
return;
}
console.log('Bye bye');
ch.providers.map((p) => p.terminate());
});
setTimeout(() => bus.broadcast({ onCustomWorkerEvent: 'worker #3' }), 100);
} else {
const client = ch.attach();
/**
* listen to events within the same sandbox
*/
client.listen('onCustomEvent', (msg) =>
console.log(`Another worker message received in ${workerData.id}; ${msg}`));
/**
* broadcast to all
*/
client.broadcast({ onCustomEvent: `Hello from ${workerData.id} 👋` });
/**
* listen to messages from message bus
*/
client.listen('onCustomWorkerEvent', (id) => {
if (workerData.id === id) {
client.broadcast({ shutdownWorker: true });
}
});
}