MST

星途 面试题库

面试题:Python异步编程之高级难度:asyncio 库中的任务优先级管理

在使用Python的asyncio库进行异步编程时,默认情况下任务是按照FIFO(先进先出)的顺序执行的。假设你现在需要实现一个任务调度器,其中不同任务具有不同的优先级,高优先级任务优先执行。请描述实现思路,并给出关键代码片段来展示如何在asyncio框架下实现任务优先级管理。
26.1万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 任务定义:创建一个任务类,除了任务本身的协程,还包含优先级属性。
  2. 优先级队列:使用Python的heapq模块来创建一个优先级队列,该队列会按照任务优先级排序。
  3. 调度器:创建一个调度器函数,该函数从优先级队列中取出任务并执行。
  4. 事件循环:在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())

在上述代码中:

  1. PriorityTask类定义了任务及其优先级,__lt__方法用于在优先级队列中比较任务优先级。
  2. scheduler函数负责从优先级队列task_queue中取出任务并执行。
  3. main函数中,创建了不同优先级的任务并添加到优先级队列中,最后运行调度器。