title: Killing node.js workers after function is done
body: <p>I'm a total node.js newbie who's just started tinkering with it. I have a piece of code that executes a function that processes strings on all cpu cores, and I wish to determine which worker completed the function first by it's id, and after that kill every worker (or just exit node).</p>
  
  <p>Here's the simplified code of my program:</p>
  
  <pre><code>var cluster = require('cluster'),
      cpus = require("os").cpus().length, // 4 cores
      myArray = ["foo","bar","baz","qux"]; // 1 string per core
  
  if (cluster.isMaster) {
      for (var i = 0; i &lt; cpus; i++) {
          var worker = cluster.fork();
      }
      cluster.on('exit', function(worker, code, signal) {
          console.log('worker ' + worker.process.pid + ' died');
      });
  } else if (cluster.isWorker) {
      computeString(myArray[cluster.worker.id]);
  }
  
  function computeString() {
      // Code to compute...
  }
  </code></pre>
  
  <p>This code works, and the computeString() function finishes much faster than executing it outside the</p>
  
  <pre><code>else if (cluster.isWorker) {}
  </code></pre>
  
  <p>So the problem is that after one worker/process completes the function, node waits until every process has done their job and doesn't terminate after those either, every process stay idle until I hit ctrl+c.</p>
  
  <p>My approach was:</p>
  
  <pre><code>function computeString() {
      // Code to compute...
      if (done) {
           console.log("Worker #" + cluster.worker + " completed the task!");
           for (var id in cluster.workers) {
              cluster.workers[id].kill();
           }
       }
  }
  </code></pre>
  
  <p>But since I'm asking here, it obviously doesn't work :)</p>