Home >Web Front-end >JS Tutorial >Quickly master the Node.js event-driven model_node.js

Quickly master the Node.js event-driven model_node.js

WBOY
WBOYOriginal
2016-05-16 15:09:571039browse

1. Traditional thread network model

Before understanding the Node.js event-driven model, we first understand the traditional thread network model. After a request enters the web server (IIS, Apache), a thread will be allocated in the thread pool to complete the request processing linearly and synchronously until The request processing is completed and a response is issued, and the thread pool is recycled after completion.

This will bring about the following problems:

1. Due to the limited number of threads in the thread pool, there will be waiting for frequent requests, and in severe cases, the server may even hang up

2. For high concurrency, locks will be used to prevent dirty data from appearing. Some I/O transactions may take a long time, which will cause some threads to wait, which is inefficient

2. Event-driven model

1. There is an event queue in Node.js. Each task will be put into the event queue, and a callback function will be left to process the results. The event loop thread (personally feels a bit similar to RunLoop in ios) processes the event queue. tasks in the task until the callback function no longer exists.

2. In the case of non-blocking, it is put into the event queue as a function with a callback, and is extracted and executed in the event loop thread.

3. When encountering I/O blocking during execution (reading files, querying databases, requesting sockets, accessing remote services, etc.), the event loop thread will not stop waiting for the result, but will continue to execute the queue. The next task in will not be executed in the event loop thread. When a function is executed, Node.js places callback functions in the event queue, and their order is determined by how quickly the function completes.

4. As mentioned in 1, when encountering I/O blocking, the loop thread will not wait for the result, but will instead execute the next task in the queue. So who should perform this I/O operation?

Node.js uses event callbacks to avoid waiting for blocking I/O and implements a thread pool in the background. When encountering an I/O blocking task, it will obtain a thread from the thread pool and put the function and callback in Executed there, the callback function executing on the blocked thread can still add events to the event queue.

The above is all about the Node.js event-driven model. I hope it will be helpful to everyone's learning.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn