您将如何根据用户输入创建 X 数量的工作线程?

How would you create X amount of worker threads based on user input?

例如,用户输入 10,然后创建 10 个工作线程 运行 一个函数。 我不知道该怎么做,我已经查看了文档,但我一头雾水。

好的,首先,您必须获取用户输入 (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 !')
})

您可以在此处的工作线程上记录自己:https://nodejs.org/api/worker_threads.html

在 Readline 上:https://nodejs.org/api/readline.html