Thread in an event-driven vs non-event driven web server

后端 未结 2 1649
滥情空心
滥情空心 2021-01-31 06:17

The following two diagrams are my understanding on how threads work in a event-driven web server (like Node.js + JavaScript) compared to a non-event driven web server (like IIS

相关标签:
2条回答
  • 2021-01-31 07:03

    The best way to picture NodeJS is like a furious squirrel (i.e. your thread) running in a wheel with an infinite number of pigeons (your I/O) available to pass messages around.

    I/O in node is "free". Your squirrel works to set up the connection and send the pigeon off, then can go on to do other things while the pigeon retrieves the data, only dealing with the data when the pigeon returns.

    If you write bad code, you can end up having the squirrel waiting for each pigeon.

    So always write non-blocking i/o code.

    If you can encourage your Pigeons to promise to come back ;)

    Promises and generators are probably the best approach you can take to this.

    HOWEVER you can always use Node cluster to establish a master squirrel that will procreate child squirrels based on the number of CPUs the master squirrel can find to dole out the work.

    Hope this helps and note the complete lack of a car analogy.

    0 讨论(0)
  • 2021-01-31 07:13
    1. Node may use threads for IO. The JS code runs in a single thread, but all the IO requests are running in parallel threads. If you want some JS code to run in parallel threads, use thread-a-gogo or some other packages out there which mitigate that behaviour.

    2. Same as 1., threads are created by Node for IO operations.

    3. You don't have to handle threading, unless you want to. Easier to develop. At least that's my point of view.

    4. A node application can be coded to run like another web server. Typically, JS code runs in a single thread, but there are ways to make it behave differently.

    Personally, I recommend threads-a-gogo (the package name isn't that revealing, but it is easy to use) if you want to experiment with threads. It's faster. Node also supports multiple processes, you may run a completely separate process if you also want to try that out.

    0 讨论(0)
提交回复
热议问题