asyncio事件循环是如何工作的?如何自定义事件循环?

进阶

答题要点

import asyncio
from asyncio import AbstractEventLoop

# 事件循环基本使用
async def main():
    print("Start")
    await asyncio.sleep(1)
    print("End")

# 获取和运行事件循环
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

# Python 3.7+推荐
asyncio.run(main())

# 事件循环底层机制
class SimpleEventLoop:
    def __init__(self):
        self.ready = []  # 就绪的回调
        self.scheduled = []  # 定时回调

    def call_soon(self, callback, *args):
        self.ready.append((callback, args))

    def call_later(self, delay, callback, *args):
        time = asyncio.get_event_loop().time() + delay
        self.scheduled.append((time, callback, args))
        self.scheduled.sort(key=lambda x: x[0])

    def run_forever(self):
        while self.ready or self.scheduled:
            # 处理定时任务
            now = asyncio.get_event_loop().time()
            while self.scheduled and self.scheduled[0][0] <= now:
                _, callback, args = self.scheduled.pop(0)
                self.ready.append((callback, args))

            # 执行就绪回调
            if self.ready:
                callback, args = self.ready.pop(0)
                callback(*args)

# 自定义协程调度
async def producer(queue):
    for i in range(5):
        await queue.put(i)
        await asyncio.sleep(0.1)

async def consumer(queue):
    while True:
        item = await queue.get()
        print(f"Consumed: {item}")
        queue.task_done()

async def main():
    queue = asyncio.Queue()
    producer_task = asyncio.create_task(producer(queue))
    consumer_task = asyncio.create_task(consumer(queue))

    await producer_task
    await queue.join()
    consumer_task.cancel()

# uvloop高性能事件循环
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题