Perhaps somebody who implemented node.js module can explain the protocol between node.js queue processed on a single thread and a blocking IO operations that will be performed by a module.
I suspect that it goes something like this:
- node.js thread registers a callback in a form of a closure and saves it with some correlation id.
- node.js invokes a method (which should perform blocking IO) on a module and passes method parameters and correlation id to it.
- module method spins off a thread and blocks on IO operation.
- when IO operation completes, modules' thread calls back to node.js thread and passes results and correlation id to it.
- node.js thread finds stored callback closure by correlation id and invokes it with result returned from module.
Question 1: Is above sequence correct?
Question 2: What exactly is node.js queue? Is it the part where epoll, kqueue or IO completion port on windows is used? Is it a callback mechanism for module to notify node.js thread that some IO had finished? How does it work?
Node.js doesn't really manage any of this quite as you speculated. It instead relies on the OSs to do most of the async IO. It uses select/epoll/kqueue depending on the operating system. "They" just put a call out and the OS calls back with a stream, chunks, etc... As far as the evented portion of it, this is built into V8, it does all the work tieing callbacks to specific events same as it does in the browser. Finally, you can look into libuv, which was written along with node and is now all maintained by Joyent. It's open source on Github so you can browse through the code if you really want the details =D
I highly suspect that Node.JS goes the same route as Twisted and uses only non-blocking IO and greenlets. OS threads seem pretty inefficient for this sort of thing.
来源:https://stackoverflow.com/questions/8575442/internals-of-node-js-how-does-it-actually-work