cpt*_*i20 5 javascript node.js libuv
我试图了解nodeJS中的线程池。通过创建运行代码process.env.UV_THREADPOOL_SIZE = 5;
process.env.UV_THREADPOOL_SIZE = 5;
const https = require('https');
const crypto = require('crypto');
const fs = require('fs');
const start = Date.now()
function doRequest() {
https.request('https://google.com', res => {
res.on('data', () => {});
res.on('end', () => {
console.log('Request:', Date.now() - start)
})
})
.end()
}
function doHash(){
crypto.pbkdf2("a", "b", 100000, 512, 'sha512', () => {
console.log("Hash:", Date.now() - start);
})
}
doRequest();
fs.readFile('multitask.js', 'utf8', () => {
console.log('fs:', Date.now() - start)
});
doHash();
doHash();
doHash();
doHash();Run Code Online (Sandbox Code Playgroud)
我在终端中得到输出:
$ node multitask.js
Request: 641
Hash: 4922
fs: 4925
Hash: 5014
Hash: 5039
Hash: 6512Run Code Online (Sandbox Code Playgroud)
在将线程池大小更改为1后,我得到了相同的输出。
Request: 501
Hash: 4025
fs: 4028
Hash: 4087
Hash: 4156
Hash: 5079Run Code Online (Sandbox Code Playgroud)
谁能告诉我问题出在哪里?
Mar*_*nde 12
在 linux 上你的代码工作正常:
UV_THREADPOOL_SIZE = 1;
fs: 20
Request: 108
Hash: 817
Hash: 1621
Hash: 2399
Hash: 3175
Run Code Online (Sandbox Code Playgroud)
UV_THREADPOOL_SIZE = 5
fs: 11
Request: 120
Hash: 836
Hash: 857
Hash: 859
Hash: 871
Run Code Online (Sandbox Code Playgroud)
如果您使用的是 windows,而不是在您的 javascript 文件中设置它,您必须在调用脚本之前设置它。
set UV_THREADPOOL_SIZE=1 & node app.js
Run Code Online (Sandbox Code Playgroud)
对我来说最简单的解决方案就是添加一个 npm 脚本条目,如下所示:
{
...
"main": "app.js",
"scripts": {
"start": "set UV_THREADPOOL_SIZE=2 & node app.js"
},
...
}
Run Code Online (Sandbox Code Playgroud)
然后,在cmd中:
npm run start
Run Code Online (Sandbox Code Playgroud)