search

Home  >  Q&A  >  body text

node.js - 理论讨论:nodejs的单线程问题

很久以前只有单线程
后来发展成多线程
而现在单线程又开始流行nodejs

1现在的单线程的语言和最早的单线程有什么区别
2还有多线程是否依然在流行,会否被单线程取代?

PHPzPHPz2785 days ago668

reply all(1)I'll reply

  • 黄舟

    黄舟2017-04-17 14:53:33

    1. The earliest single-threaded codes were all synchronized codes, which were very inefficient. The program was always blocked waiting for synchronization results. But the single thread mentioned by 现在, such as nodejs, is asynchronous. It will not wait for the call result, but instead executes other things. When the call result returns, it will continue to execute the program after obtaining the result.

    2. Multi-threading is of course popular. The efficiency of multi-threaded programs is much higher than that of single-threading when the amount of concurrency is high. It also has advantages when tasks are divided. Of course, in order to make full use of machine resources, single-threaded ideas have also been developed that use multiple cores of the CPU. For example, the nodejs module of cluster. However, although the cluster module uses multiple cores to increase the number of processes corresponding to the number of cores, each process is independent of each other and shares a port. But if it is a multi-process program such as Java, the processes have shared resources, which will occupy less memory.

    3. Each has its own advantages, and they will only make up for it and move forward. There may be new models to replace it! Personal opinion. Hope this helps! !

    • Attached is an example of cluster

    const cluster = require('cluster');
    const http = require('http');
    const numCPUs = require('os').cpus().length;
    
    if (cluster.isMaster) {
      // Fork workers.
      for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
      }
    
      cluster.on('exit', (worker, code, signal) => {
        console.log(`worker ${worker.process.pid} died`);
      });
    } else {
      // Workers can share any TCP connection
      // In this case it is an HTTP server
      http.createServer((req, res) => {
        res.writeHead(200);
        res.end('hello world\n');
      }).listen(8000);
    }

    This program will start a node process corresponding to the number of CPU cores and listen on port 8000

    reply
    0
  • Cancelreply