在Ubuntu系统中,使用Node.js实现并发处理可以通过以下几种方式:
const fs = require('fs').promises;
async function readFiles() {
try {
const file1 = await fs.readFile('file1.txt', 'utf-8');
const file2 = await fs.readFile('file2.txt', 'utf-8');
console.log(file1, file2);
} catch (error) {
console.error(error);
}
}
readFiles();
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
// Workers can share any TCP connection
// In this case it is an HTTP server
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}
const { Worker, isMainThread, parentPort } = require('worker_threads');
if (isMainThread) {
// This code is executed in the main thread
const worker = new Worker(__filename);
worker.on('message', (message) => {
console.log('Message from worker:', message);
});
} else {
// This code is executed in the worker thread
parentPort.postMessage('Hello from worker!');
}
通过以上方法,你可以在Ubuntu系统中使用Node.js实现并发处理,提高应用程序的性能和响应速度。