Benang Pekerja mendayakan keselarian sebenar dalam Node.js, sesuai untuk tugas intensif CPU. Jom selami.
const { Worker, isMainThread, parentPort } = require('worker_threads'); if (isMainThread) { const worker = new Worker(__filename); worker.on('message', (msg) => console.log('From worker:', msg)); worker.postMessage('Hello, Worker!'); } else { parentPort.on('message', (msg) => { console.log('From main:', msg); parentPort.postMessage('Hello, Main!'); }); }
const { Worker } = require('worker_threads'); const worker = new Worker('./worker.js'); const sharedBuffer = new SharedArrayBuffer(4); const arr = new Int32Array(sharedBuffer); arr[0] = 123; worker.postMessage({ sharedBuffer });
const { StaticPool } = require('node-worker-threads-pool'); const pool = new StaticPool({ size: 4, task: (n) => n * 2 }); async function runTasks() { const results = await Promise.all([ pool.exec(10), pool.exec(20), pool.exec(30) ]); console.log(results); // [20, 40, 60] } runTasks().catch(console.error);
Benang Pekerja bersinar untuk pemprosesan selari tugas intensif CPU. Gunakan dengan bijak untuk mengecas aplikasi Node.js anda.
Sore?
Atas ialah kandungan terperinci Melancarkan Pemprosesan Selari dengan Benang Pekerja Node.js. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!