面试题答案
一键面试实现思路
- 任务定义:创建一个任务类,除了任务本身的协程,还包含优先级属性。
- 优先级队列:使用Python的
heapq
模块来创建一个优先级队列,该队列会按照任务优先级排序。 - 调度器:创建一个调度器函数,该函数从优先级队列中取出任务并执行。
- 事件循环:在
asyncio
的事件循环中运行调度器。
关键代码片段
import asyncio
import heapq
class PriorityTask:
def __init__(self, priority, coro):
self.priority = priority
self.coro = coro
def __lt__(self, other):
return self.priority < other.priority
async def scheduler(task_queue):
while task_queue:
task = heapq.heappop(task_queue)
await task.coro
async def main():
task_queue = []
# 添加不同优先级任务
heapq.heappush(task_queue, PriorityTask(2, asyncio.sleep(1, result="Task with priority 2")))
heapq.heappush(task_queue, PriorityTask(1, asyncio.sleep(1, result="Task with priority 1")))
heapq.heappush(task_queue, PriorityTask(3, asyncio.sleep(1, result="Task with priority 3")))
await scheduler(task_queue)
if __name__ == "__main__":
asyncio.run(main())
在上述代码中:
PriorityTask
类定义了任务及其优先级,__lt__
方法用于在优先级队列中比较任务优先级。scheduler
函数负责从优先级队列task_queue
中取出任务并执行。- 在
main
函数中,创建了不同优先级的任务并添加到优先级队列中,最后运行调度器。