eventLoop

what

Event Loop是一个程序结构,用于等待和发送消息和事件

a programming construct that waits for and dispatches events or messages in a program.

简单说,就是在程序中设置两个线程:一个负责程序本身的运行,称为"主线程";另一个负责主线程与其他进程(主要是各种I/O操作)的通信,被称为"Event Loop线程"(可以译为"消息线程")。
在这里插入图片描述

由上图可以清楚知道Node的单线程指的是主线程为单线程

异步执行

// test.js
setTimeout(() => console.log(1));
setImmediate(() => console.log(2));
process.nextTick(() => console.log(3));//异步最快
Promise.resolve().then(() => console.log(4));
(() => console.log(5))();//同步任务最早执行
//53412

异步分为两种:

  • 本轮循环:process.nextTick(),Promise
  • 次轮循环:setTimeout(),setInterval,setImmediate

在这里插入图片描述

每一次循环中,setTimeout等次轮循环在timers阶段执行,而本轮循环就在check阶段执行,所以会先展示

An event loop is a programming construct that allows for the handling of asynchronous operations in a program. It works by waiting for and dispatching events or messages in a program. Specifically, an event loop listens for events, such as user input or network requests, and then calls the appropriate callback function to handle the event[^1]. In the context of programming, especially in languages that support asynchronous programming like Python, the event loop is crucial for managing multiple operations without blocking the execution of the program. When an event occurs, the event loop picks it up and executes the associated handler. This is particularly useful in applications that require high concurrency, such as web servers or GUI applications, where the program must respond to various inputs and events from users or external systems[^1]. For example, in a web browser, the event loop handles user interactions like clicks and keystrokes, as well as rendering updates and network requests. Similarly, in a server-side application, the event loop can manage multiple client connections and process their requests efficiently without the need for multi-threading. The event loop operates on a single thread, using non-blocking I/O calls, which means that it can handle many simultaneous connections and operations without the overhead of thread management. This model is often more efficient and simpler to manage than traditional multi-threaded approaches, which can suffer from issues such as race conditions and deadlocks[^1]. To illustrate, consider a simple server that needs to handle multiple client requests. Instead of creating a new thread for each client, which can be resource-intensive and complex to manage, the server can use an event loop to handle each request asynchronously. When a client sends a request, the event loop schedules the request to be processed, and once the processing is complete, the result is sent back to the client. In summary, the event loop is a fundamental concept in asynchronous programming, enabling programs to handle multiple tasks concurrently and efficiently, making it possible to build scalable and responsive applications. ```python import asyncio async def handle_client(reader, writer): data = await reader.read(100) message = data.decode() addr = writer.get_extra_info('peername') print(f"Received {message} from {addr}") print("Send: %r" % message) writer.write(data) await writer.drain() print("Close the client socket") writer.close() async def main(): server = await asyncio.start_server( handle_client, '127.0.0.1', 8888) addr = server.sockets[0].getsockname() print(f'Serving on {addr}') async with server: await server.serve_forever() asyncio.run(main()) ``` The code above demonstrates a simple asynchronous server using Python's `asyncio` library, which utilizes an event loop to handle multiple client connections concurrently.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值