javascript - Interrupting while() and finalizing gracefully Node.js -


i implementing random sampling / montecarlo heuristic travelling salesman problem. want perform maximum c iterations, while being able stop search when want ctrl+c or sending sigint process.

i know has been asked before (related: quitting node.js gracefully) given solution not working me. process doesn't exit when give ctrl+c , if kill it, finalizing code not executed.

my code:

var tsp = require("./tsp.js"); var data = tsp.load("./input/it16862.tsp");  var starting_point = data.splice(10927, 1)[0]; var c = 0; var cost = number.positive_infinity; var new_cost, solution, candidate_solution; var interrupt = false; var c = 0, interrupt = false;  process.on('sigint', function() {     interrupt = true; });  while(c < 1000000000) {     if (interrupt) {         break;     }     candidate_solution = shuffle(data);     new_cost = tsp.cost(candidate_solution, starting_point);     if (new_cost < cost) {         cost = new_cost;         solution = candidate_solution;         console.log("found new better solution! %d", cost);     }     c++; }  if (interrupt) {     console.log("caught interrupt signal"); } console.log("examined %d solutions", c); console.log("best: %j", cost); console.log("solution written to: %s", tsp.write(solution, starting_point, cost)); 

i on ubuntu 14.04.1, nodejs 4.2.4. idea might wrong?

javascript single-threaded language, there no way runtime interrupt process in middle of while loop this. process.on handler function not invoked until main event loop free, won’t happen until c >= 1000000000 because never yield.

in order work need change work loop yield node.js runtime, this:

// ... var c = 0, interrupt = false; function dowork() {   while(c < 1000000000) {       if (interrupt) {           break;       }       // yield every 10000 iterations       // allow event loop handle events       if ((c % 10000) === 0) {           setimmediate(dowork);           return;       }       candidate_solution = shuffle(data);       new_cost = tsp.cost(candidate_solution, starting_point);       if (new_cost < cost) {           cost = new_cost;           solution = candidate_solution;           console.log("found new better solution! %d", cost);       }       c++;   } }  dowork(); 

you can tune performance versus responsiveness choosing different value number of iterations between yields (higher numbers improve performance avoiding overhead caused yielding, reduce responsiveness making take longer until interrupt can acknowledged).


Comments

Popular posts from this blog

c - How to retrieve a variable from the Apache configuration inside the module? -

c# - Constructor arguments cannot be passed for interface mocks -

python - malformed header from script index.py Bad header -