Can node.js code result in race conditions?

后端 未结 6 1815
小鲜肉
小鲜肉 2020-12-02 23:01

From what I read, race conditions occur when different threads try to change a shared variable, which can result in a value that\'s not possible with any serial order of exe

6条回答
  •  长情又很酷
    2020-12-02 23:42

    Race conditions can still happen as they really have nothing to do with threads, but on making assumptions about event timing and sequence, so threads are just an example of that.

    Node.js is single-threaded, but still concurrent, and race conditions are possible. For example:

    var http = require('http');
    
    var size;
    
    http.createServer(function (req, res) {
      size = 0;
    
      req.on('data', function (data) {
        size += data.length;
      });
    
      req.on('end', function () {
        res.end(size.toString());
      })
    
    }).listen(1337, '127.0.0.1');
    

    This program is supposed to send clients a size of their request. If you test it, will seem to work correct. But it is actually based on implicit assumption, that nothing happens between request start and end events. If there are 2 or more concurrent clients it will not work.

    This happens here because size variable is shared, a lot like when two threads share a variable. You can think about an abstract "asynchrnous context", which is a lot like thread, but it can only be suspended at certain points.

提交回复
热议问题