What are the differences between event-driven and thread-based server system?
Node.js is an event driven I/O and It's a single threaded server that acts upon callbacks and never blocks on the main thread.
- But how does it manage to non-blocking I/O?
- if it does easy to manage, why don't thread-based system manage it?
- Does not work the other threads (behind single event-driven thread) as like thread-based ?
- if the other threads mean workers(behind event driven thread) are busy, how it still can handle jobs without blocking?
Thread-based model assigning a task to a thread and if there is no idle thread, block new tasks.
- if a thread can handle multiple tasks like as event-driven single thread that handles every I/O without blocking, why thread-based system doesn't use this tactic on busy threads to I/O without blocking.
I am wondering what are the differences (advantages/disadvantages) between event-driven and thread-based server systems.
The difference might be described as follows (with some simplification):
in "thread driven" runtimes, when a request comes in, a new thread is created and all the handling is done in that thread.
in "event driven" runtimes, when a request comes in, the event is dispatched and handler will pick it up. When? In Node.js, there is an "event loop" which basically loops over all the pieces of code that need to be executed and executes them one by one. So the handler will handle the event once event loop invokes it. The important thing here is that all the handlers are called in the same thread - the event loop doesn't have a thread pool to use, it only has one thread.
On the other hand, in the "thread driven" model, if the handler takes a lot of time to complete, it won't hurt other threads much, because they can run at the same time independently.
See this article (and pictures) for an explanation of the event loop.
1 Of course there is more that one thread in Node.js process, some of them are related to I/O. But your app logic is handled in one thread.