Node.js因爲JS的執行在單一線程,致使CPU密集計算的任務可能會使主線程會處於繁忙的狀態,進而影響服務的性能,雖然能夠經過child_process模塊建立子進程的方式來解決,可是一方面進程之間沒法共享內存,另外一方面建立進程的開銷也不小。因此在10.5.0版本中Node.js提供了worker_threads模塊來支持多線程,一直以來被人所詬病的不擅長CPU密集計算有望成爲歷史。
源碼 --> https://github.com/nodejs/nod...
worker_thread 模塊中有 4 個對象和 2 個類。node
const assert = require('assert'); const { Worker, MessageChannel, MessagePort, isMainThread, parentPort } = require('worker_threads'); if (isMainThread) { const worker = new Worker(__filename); const subChannel = new MessageChannel(); worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]); subChannel.port2.on('message', (value) => { console.log('received:', value); }); } else { parentPort.once('message', (value) => { assert(value.hereIsYourPort instanceof MessagePort); value.hereIsYourPort.postMessage('the worker is sending this'); value.hereIsYourPort.close(); }); }