下面我将详细讲解“node工作线程worker_threads的基本使用”的完整攻略。
- 基本介绍
Node.js是一款基于V8引擎的JavaScript环境,因其高效、轻量、可扩展性强等特点,近年来备受各大企业的青睐。Node.js使用多个事件循环线程来处理并发请求,但在单个线程下,通过worker_threads模块可以实现多线程操作,提高代码执行效率。worker_threads可以实现多进程共享内存,还可以在线程池中分配和调度线程,避免出错时导致主线程崩溃。
2.使用指南
- 创建线程池
const { Worker, isMainThread } = require('worker_threads');
const worker = new Worker(__filename);
- 子线程与主线程控制
① 子线程
if (!isMainThread) {
setInterval(() => {
console.log('子线程');
}, 2000);
}
② 主线程
if (isMainThread) {
const worker = new Worker(__filename);
setInterval(() => {
worker.postMessage('主线程');
}, 5000);
worker.on('message', (msg) => {
console.log(msg);
});
}
-父子线程执行不同任务
① 子线程
if (!isMainThread) {
const fs = require('fs');
const path = require('path');
const buffer = Buffer.alloc(1024);
worker.on('message', (filePath) => {
fs.open(filePath, 'r', (err, fd) => {
if (err) throw err;
const stats = fs.statSync(filePath);
const blockSize = 1024;
const nbBlocks = Math.ceil(stats.size / blockSize);
let i = 0;
let readNextChunk = function () {
fs.read(fd, buffer, 0, blockSize, i * blockSize, (err, bytesRead, buffer) => {
if (err) throw err;
worker.postMessage({chunk: buffer, blockSize: blockSize, nbBlocks: nbBlocks, block: i });
i++;
if (i < nbBlocks) {
readNextChunk();
} else {
worker.postMessage({end: true});
}
});
};
readNextChunk();
});
});
}
② 主线程
if (isMainThread) {
const worker = new Worker(__filename);
const path = require('path');
worker.postMessage(path.join(__dirname, './file.txt'));
worker.on('message', (msg) => {
console.log('block ' + msg.block + ' (file size: ' + (msg.nbBlocks * msg.blockSize / 1024 / 1024).toFixed(2) +
'MB ) read, percent: ' + (100 * (msg.block / msg.nbBlocks)).toFixed(1) + '%');
});
}
以上是关于“node工作线程worker_threads的基本使用”的完整攻略,希望可以帮到你。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:node工作线程worker_threads的基本使用 - Python技术站