【发布时间】:2021-09-15 14:26:57
【问题描述】:
我正在 NodeJS 上尝试多线程,并使用下面的代码进行探索
const crypto = require('crypto');
const start = Date.now();
crypto.pbkdf2('a', 'b', 100000, 512, 'sha512', () => {
console.log('1:', Date.now() - start);
});
crypto.pbkdf2('a', 'b', 100000, 512, 'sha512', () => {
console.log('2:', Date.now() - start);
});
crypto.pbkdf2('a', 'b', 100000, 512, 'sha512', () => {
console.log('3:', Date.now() - start);
});
crypto.pbkdf2('a', 'b', 100000, 512, 'sha512', () => {
console.log('4:', Date.now() - start);
});
crypto.pbkdf2('a', 'b', 100000, 512, 'sha512', () => {
console.log('5:', Date.now() - start);
});
如果我错了,请纠正我,默认情况下 libuv 的线程池大小为 4,如 here 所述。因此,通过运行上面的代码,每个crypto.pbkdf2 都被分配给单独的线程并同时运行,而第五个将等待一段时间才能运行。下面是结果
1: 484
2: 490
3: 490
4: 490
5: 963
我可以理解第五个crypto.pbkdf2 由于线程并行运行的时间增加了一倍,所以现在我正在探索增加线程池的大小。以下是我的尝试,但结果似乎相同?
$ set UV_THREADPOOL_SIZE=120 && node threads.js
2: 487
3: 492
1: 493
4: 493
5: 986
【问题讨论】:
-
将繁重的 CPU 任务放在单独的子进程中,并运行 n 子进程以并行运行代码。
标签: javascript node.js multithreading libuv