Can node.js code result in race conditions?

后端 未结 6 1796
小鲜肉
小鲜肉 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:52

    No. That's true you cannot have race condition on a single threaded, non I/O doing program.

    But node.js is mainly fast because of its non blocking way of programming. Non blocking means that setting a listener to a response event, you can do something else while waiting this response.

    Why ? Because the work for getting the response is done on another thread. Database, filesystem, run on other thread, client obviously runs on another computer and you program workflow can depend on its response.

    So strictly speaking, node.js runs on one thread, but your program workflow, wich include I/O (database, filesystem), client and everything, runs on many thread.

    So there still can be race condition if you do a request to add something to a database, and then just send a request to delete it without waiting for the response of the first request. There would be no race condition if the database was running in the same thread as node.js, and the request was just a function call executed immediatly.

提交回复
热议问题