简体   繁体   中英

How to use Nodejs multi CPU cores for multi process?

I have CPU 4 cores and I have some code like this:

setInterval(function() {
   Player.RunUpdate();
   Animal.RunUpdate();
   Bullet.RunUpdate();
   GameItems.RunUpdate();
}, 1E3 / FPS);

With each .RunUpdate() is loop like this:

for(var id in player_list){
   //check something and update postion
}

How I can use one core for one .RunUpdate() ? Is it possible? Ex:

setInterval(function() {
  core_1{
     Player.RunUpdate();
  }
  core_2{
     Animal.RunUpdate();
  }
  core_3{
     Bullet.RunUpdate();
  }
  core_4{
     GameItems.RunUpdate();
}, 1E3 / FPS);

Thanks for reading!

You can use cluster npm, so it will use all cpu cores.

Using cluster it will create co worker

Ref code click here

As I can understand that you want to use the CPU core i will suggest you run below code.

save it as server.js then run it using node command like "node server.js".

In the below code, suppose your CPU having 4 core then this code will create 4 threads ( because of you CPU have 4 core by this line of code require('os').cpus().length ).

And this makes your program execution 4 times faster. now you can assume that how you can use you CPU's core accordingly.

var http = require('http');
var cluster = require('cluster');
var numCPU = require('os').cpus().length;

if (cluster.isMaster) {
    console.log(`Master ${process.pid} is running`);

    for (let i = 0; i < numCPU; i++) {
        console.log('' + i + '.' + cluster.fork());
    }

    cluster.on('exit', (worker, code, signal) => {
        console.log(`Worker ${worker.process.pid} died.`);
    });

} else {
    http.createServer((req, res) => {
        res.writeHead(200, { 'content-type': 'plain/text' });
        res.end('Hello cluster');
    }).listen(8000, () => {
        console.log('server is running on 8000');
    });
    console.log(`Worker ${process.pid} started`);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM