3

I'm creating some algorithms that are very performance heavy, e.g. evolutionary and artificial intelligence. What matters to me is that my update function gets called often (precision), and I just can't get setInterval to update faster than once per millisecond.

Initially I wanted to just use a while loop, but I'm not sure that those kinds of blocking loops are a viable solution in the Node.js environment. Will Socket.io's socket.on("id", cb) work if I run into an "infinite" loop? Does my code somehow need to return to Node.js to let it check for all the events, or is that done automatically?

And last (but not least), if while loops will indeed block my code, what is another solution to getting really low delta-times between my update functions? I think threads could help, but I doubt that they're possible, my Socket.io server and other classes need to somehow communicate, and by "other classes" I mean the main World class, which has an update method that needs to get called and does the heavy lifting, and a getInfo method that is used by my server. I feel like most of the time the program is just sitting there, waiting for the interval to fire, wasting time instead of doing calculations...

Also, I'd like to know if Node.js is even suited for these sorts of tasks.

4
  • Is update used as a callback for some asynchronous processing? Commented Aug 22, 2012 at 14:03
  • The update is a callback of setInterval, so yes. Commented Aug 22, 2012 at 14:06
  • what i am getting at is 1) what does your update do? and 2) where are the (blocking) calculations performed? Commented Aug 22, 2012 at 14:10
  • I'm simulating virtual environments, like Polyworld. Currently, I was just writign the server code and some other things, so the algorithms aren't yet implemented. Think a scene with physics, up to a 1000 objects. These objects are animals, each with its own neural network. Basically, shorter the delta time, more precision in my simulation. Commented Aug 22, 2012 at 14:17

1 Answer 1

9

You can execute havy algorithms in separate thread using child_process.fork and wait results in main thread via child.on('message', function (message) { });

app.js

var child_process = require('child_process');
var child = child_process.fork('./heavy.js', [ 'some', 'argv', 'params' ]);
child.on('message', function(message) {
     // heavy results here
});

heavy.js

while (true) {
    if (Math.random() < 0.001) {
        process.send({ result: 'wow!' });
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.