【问题标题】:How would you create X amount of worker threads based on user input?您将如何根据用户输入创建 X 数量的工作线程?
【发布时间】:2020-11-13 15:39:49
【问题描述】:

例如,用户输入 10,创建了 10 个运行函数的工作线程。 我无法弄清楚如何做到这一点,我已经查看了文档并且我正在空白。

【问题讨论】:

    标签: node.js multithreading node-worker-threads


    【解决方案1】:

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

    在这里阅读在线:https://nodejs.org/api/readline.html

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 2021-03-18
      • 2015-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 2017-09-11
      相关资源
      最近更新 更多