-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy paththread.js
More file actions
28 lines (23 loc) · 758 Bytes
/
Copy paththread.js
File metadata and controls
28 lines (23 loc) · 758 Bytes
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
import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';
const wasteTime = (delay) => {
const end = Date.now() + delay;
while (Date.now() < end) { }
};
if (isMainThread) {
console.log('starting main thread');
const worker = new Worker('./thread.js', { workerData: { delay: 2000 } });
worker.on('message', msg => {
console.log(`from worker thread ${msg}`);
});
worker.postMessage('hello!!');
console.log('ending main thread');
} else {
parentPort.on('message', msg => {
console.log(`from main thread - ${msg}`);
})
parentPort.postMessage('starting');
wasteTime(workerData.delay);
parentPort.postMessage('in middle of thread');
wasteTime(workerData.delay);
parentPort.postMessage('all done');
}