This article mainly introduces Node in detail. the js event-driven model first describes the traditional thread network model, and then learns about Node. js event-driven model. For more information, see
I. Traditional Thread Network Model
Learn about Node. before using the js event-driven model, let's take a look at the traditional Thread Network Model. After a request enters the web Server (IIS, Apache, A thread will be allocated to the thread pool for linear synchronization to complete request processing until the request processing is complete and a response is sent. After the completion, the thread pool recycles the request.
This will bring about the following problems:
1. Due to the limited number of threads in the thread pool, the server may be suspended even when frequent requests occur.
2. when high concurrency occurs, some I/O transactions may take a long time to prevent dirty data from being resolved using locks. In this way, some threads wait and the efficiency is low.
Ii. event-driven model
1. in Node. there is an event queue in js. Every task will be put into the event queue, and the callback function of the processing result will be left. The event loop thread (which is similar to RunLoop in ios) processes tasks in the event queue, until the callback function no longer exists.
2. Without blocking, a function with callback is put into the event queue, and the event loop thread is extracted and executed.
3. when I/O blocking (Reading files, querying databases, requesting sockets, and accessing remote services) occurs during execution, the event loop thread does not stop waiting for the results, instead, the next task in the queue will not be executed in the event loop thread. During function execution, Node. js places the callback function in the event queue. The order of the callback function is determined by the function completion speed.
4. When I/O congestion occurs in 1, the loop thread does not wait for the result, but instead executes the next task in the queue. Who should execute this I/O operation?
Node. js uses Event Callback to avoid waiting for blocked I/O. It implements a thread pool in the background. When an I/O blocking task is encountered, it obtains a thread from the thread pool, when this function and callback are executed, the callback function executed on the blocked thread can still add the event to the event queue.
The above is all about the Node. js event-driven model. I hope it will be helpful for your learning.