Skip to content

Instantly share code, notes, and snippets.

@peterbean410
Last active November 1, 2024 16:15
Show Gist options
  • Save peterbean410/67ec29cc65a0a9ee0bc9efea15b4da61 to your computer and use it in GitHub Desktop.
Save peterbean410/67ec29cc65a0a9ee0bc9efea15b4da61 to your computer and use it in GitHub Desktop.
worker_thread.js
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
if (isMainThread) {
// This code runs in the main thread
const worker = new Worker(__filename, {
workerData: { number: 5 } // Send data to the worker thread
});
worker.on('message', (result) => {
console.log(`Result from worker thread: ${result}`);
});
worker.on('error', (err) => {
console.error(err);
});
worker.on('exit', (code) => {
if (code !== 0)
console.log(`Worker stopped with exit code ${code}`);
});
} else {
// This code runs in the worker thread
async function init() {
console.log(1);
await sleep(1000);
console.log(2);
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
const { number } = workerData;
const result = fibonacci(number); // Perform some CPU-intensive task
parentPort.postMessage(result); // Send the result back to the main thread
(async function() {
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
console.log(1)
await sleep(10000)
console.log(2)
await sleep(20000)
console.log(3)
})()
}
function fibonacci(n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
#!/usr/bin/env bash
echo "Running node process in background"
node worker_thread.js &
echo "Print out LWP of the node process"
node_pid=$(ps -o ppid,spid,pid,comm -Tx | grep node | awk 'FNR==1{print $3}')
ps -o ppid,spid,pid,comm -T -p $node_pid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment