Search code examples
node.jsmultithreadingnode-worker-threads

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


For example, a user inputs 10, and 10 worker threads are created that run a function. I cannot figure out how to do this, i've looked at the docs and i'm blanking.


Solution

  • Okay so, first, you'll have to get user input (stdin), parse it and store it into a variable.

    Then, you'll launch N workers with a for loop.

    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 !')
    })
    

    You can document yourself on Worker threads here : https://nodejs.org/api/worker_threads.html

    And on Readline here : https://nodejs.org/api/readline.html