Last active
December 19, 2024 16:26
-
-
Save ErickWendel/59aa568e09aff06a90c0a71bbef5c6e5 to your computer and use it in GitHub Desktop.
Nodejs threads creating threads - demonstrates that if the intermediary thread dies, the child thread can't access the main thread
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Worker, isMainThread, parentPort, threadId } = require('worker_threads'); | |
if (isMainThread) { | |
const worker = new Worker(__filename); | |
worker.on('message', (msg) => { | |
console.log(`${msg}`); | |
}); | |
worker.postMessage('main >'); | |
} else { | |
parentPort.on('message', (message) => { | |
const innerWorker = new Worker('./thread2.js'); | |
innerWorker.postMessage(message + threadId + '> '); | |
innerWorker.on('message', (msg) => { | |
parentPort.postMessage(msg) | |
}); | |
setTimeout(() => { | |
innerWorker.terminate() | |
}, 2000); | |
}); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Worker, isMainThread, parentPort, threadId } = require('worker_threads'); | |
if (isMainThread) { | |
} else { | |
parentPort.on('message', (message) => { | |
const innerWorker = new Worker('./thread3.js'); | |
innerWorker.postMessage(message + threadId + '> '); | |
innerWorker.on('message', (msg) => { | |
parentPort.postMessage(msg) | |
}); | |
}); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Worker, isMainThread, parentPort, threadId } = require('worker_threads'); | |
if (isMainThread) { | |
} else { | |
parentPort.on('message', (message) => { | |
// This works even with sync execution | |
// let lastExecuted = Date.now(); | |
// while (true) { | |
// if (Date.now() - lastExecuted > 900) { | |
// parentPort.postMessage(message + threadId); | |
// lastExecuted = Date.now(); | |
// } | |
// } | |
setInterval(() => { | |
parentPort.postMessage(message + threadId); | |
}, 1000); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment