Created
June 24, 2024 10:31
-
-
Save kelgendy1204/1b2aa66840977c339bdd46408d30905c to your computer and use it in GitHub Desktop.
Blocking event loop in nodejs for different threads
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 { parentPort } = require('worker_threads'); | |
function blockForSeconds(seconds) { | |
const startTime = Date.now(); | |
let endTime = startTime; | |
while (endTime - startTime < seconds * 1000) { | |
endTime = Date.now(); | |
} | |
} | |
setTimeout(() => { | |
blockForSeconds(2); | |
parentPort.postMessage(1); | |
}, 1000); | |
setTimeout(() => { | |
parentPort.postMessage(1.5); | |
}, 1500); |
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 } = require('worker_threads'); | |
const path = require('path'); | |
function run() { | |
const startTime = performance.now(); | |
const worker = new Worker(path.join(__dirname, './blocking-task.js')); | |
worker.on('message', (time) => { | |
const endWorkerTime = performance.now(); | |
const executionTime = endWorkerTime - startTime; | |
console.log(`Other Thread ${time} seconds timeout with one time 2 seconds block execution time: ${executionTime.toFixed(3)} milliseconds`); | |
}); | |
setTimeout(() => { | |
const endWorkerTime = performance.now(); | |
const executionTime = endWorkerTime - startTime; | |
console.log(`Main thread 1.5 second timeout execution time: ${executionTime.toFixed(3)} milliseconds`); | |
}, 1500); | |
} | |
run(); | |
/* | |
* Results: | |
* Main thread 1.5 second timeout execution time: 1505.867 milliseconds | |
* Other Thread 1 seconds timeout with one time 2 seconds block execution time: 3021.362 milliseconds | |
* Other Thread 1.5 seconds timeout with one time 2 seconds block execution time: 3021.531 milliseconds | |
* | |
* Results shows that every thread handle its own tasks on a specific event loop | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment