Created
July 17, 2019 08:47
-
-
Save dylanbr/3ecf396055d6a425a9160a8ec37ccc79 to your computer and use it in GitHub Desktop.
Node 12 worker 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
// To run: node --no-warnings --experimental-modules index.js | |
import { | |
Worker, | |
isMainThread, | |
parentPort, | |
workerData, | |
} from 'worker_threads'; | |
import { basename } from 'path'; | |
import { fileURLToPath } from 'url'; | |
const scriptFilename = basename(fileURLToPath(import.meta.url)); | |
if (isMainThread) { | |
const worker = new Worker(`./${scriptFilename}`, { | |
workerData: 'Hello!', | |
}); | |
worker.on('message', (data) => { | |
console.log('parent:', data); | |
}); | |
worker.on('online', () => { | |
console.log('parent: Child spotted.'); | |
}); | |
worker.on('exit', () => { | |
console.log('parent: Farewell.'); | |
}); | |
} else { | |
console.log('child:', workerData); | |
parentPort.postMessage('And hello to you!'); | |
console.log('child: Good bye.'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment