【发布时间】:2020-11-13 15:39:49
【问题描述】:
例如,用户输入 10,创建了 10 个运行函数的工作线程。 我无法弄清楚如何做到这一点,我已经查看了文档并且我正在空白。
【问题讨论】:
标签: node.js multithreading node-worker-threads
例如,用户输入 10,创建了 10 个运行函数的工作线程。 我无法弄清楚如何做到这一点,我已经查看了文档并且我正在空白。
【问题讨论】:
标签: node.js multithreading node-worker-threads
好的,首先,您必须获取用户输入 (stdin),对其进行解析并将其存储到变量中。
然后,您将使用 for 循环启动 N 个 worker。
const readline = require('readline');
const Worker = require('worker_threads')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
process.stdout.write('How many threads to start ? ')
rl.on('line', (line) => {
// Here, line is the user input
if(!isNaN(line)) {
const n = Number(line)
for(let i = 0;i < n;i++) {
new Worker("filename")
}
}
else throw Error('Input is not a valid number !')
})
您可以在此处在 Worker 线程上记录自己:https://nodejs.org/api/worker_threads.html
【讨论】: