EventLoop

答案:

了解几个概念:调用栈、同步/异步任务、宏任务/微任务

JavaScript本身是单线程,也就是同一时刻只能干一件事,JS任务包含了同步任务和异步任务,遇到执行函数会将其放入调用栈(先进后出)中,遇到setTimeout/setInterval等异步任务时,会把它放入到消息队列中,等主线程的任务执行完成以后,再回过头执行消息队列中的异步任务,如果异步任务中仍然有异步任务,会继续放入消息队列,以此类推,便形成了一个事件循环。

异步任务:

  • setTimeout

  • setInterval

异步任务又分为宏任务和微任务,promise就属于微任务。

 

详细解析:

Event Loop即事件循环,是指浏览器或Node的一种解决javaScript单线程运行时不会阻塞的一种机制。

调用栈(Call Stack)

  是一种 LIFO(Last In, First Out)的数据结构,特点即 后进先出

调用栈 本质上当然还是个栈,关键在于它里面装的东西,是一个个待执行的函数。

Event Loop 会一直检查 Call Stack 中是否有函数需要执行,如果有,就从栈顶依次执行。同时,如果执行的过程中发现其他函数,继续入栈然后执行。

先拿两个函数来说:

  • 栈空
  • 现在执行到一个 函数A,函数A 入栈
  • 函数A 又调用了 函数B,函数B 入栈
  • 函数B 执行完后 出栈
  • 然后继续执行 函数A,执行完后A也 出栈
  • 栈空

 

Javascript 有一个 main thread 主线程和 call-stack 调用栈(执行栈),所有的任务都会被放到调用栈等待主线程执行。

event-loop-process.png

  • 开始,任务先进入 Call Stack
  • 同步任务直接在栈中等待被执行,异步任务从 Call Stack 移入到 Event Table 注册
  • 当对应的事件触发(或延迟到指定时间),Event Table 会将事件回调函数移入 Event Queue 等待
  • 当 Call Stack 中没有任务,就从 Event Queue 中拿出一个任务放入 Call Stack

而 Event Loop 指的就是这一整个圈圈:

它不停检查 Call Stack 中是否有任务(也叫栈帧)需要执行,如果没有,就检查 Event Queue,从中弹出一个任务,放入 Call Stack 中,如此往复循环。
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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值