1

When I receive an "on" event on the server side, I want to start a task in parallel so it does not block the current event loop thread. Is it possible to do so? How?

I don't want to block the server side loop and I want to be able to send back a message to the client once the task is done, something such as:

client.on('execute-parallel-task', function(msg) {
    setTimeout(function() {
        // do something that takes a while
        client.emit('finished-that-task');
    },0);
    // this block should return asap, not waiting for the previous call
});

I am not sure if setTimeout will do the job.

4

2 回答 2

2

It depends what the takes a while is. If it takes a while asynchronously (you can tell because you'll have to register a callback or complete handler), and takes a while because it's blocked on something like IO, rather than CPU bound, it'll inherently be parallel.

If however, its something synchronous or CPU bound, whilst you can use setTimeout, setImmediate etc. to send back a message immediately, once the handler for setTimeout or setImmediate executes, your single thread of execution will be stuck handling that; you're not really fixing the problem, merely deferring it.

To exhibit true parallel behaviour, you'll need to launch a child process. You can use the message passing functionality to notify your worker what work to do, and to notify the parent process once the work is complete.

var cp = require('child_process');
var child = cp.fork(__dirname + '/my-child-worker.js');

n.on('message', function(m) {
  if (m === "done") {
      // Whey!
  }
});

n.send(/* Job id, or something */);

Then in my-child-worker.js;

process.on('message', function (m) {
    switch (m) {
        case 'get-x':
            // blah
        break;
        // other jobs
    }

    process.send('done');
});
于 2013-05-26T21:07:02.530 回答
1

you do not need the setTimeout. Your function(msg) will be called once the execute parallel task finishes.

if you are designing a task to run in an async manner, you can look at something like the async lib for node.js

Async Node JS Link

于 2013-05-26T21:03:13.633 回答