蓝色天空网mbsky.com · 知识 · 实践 · 创造Python · 本地阅读预览
教程 / Python / 数据科学 / Python

Python asyncio:协程调度、等待与取消

用本机网络请求和固定输入观察任务何时暂停、何时继续,以及怎样收尾。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

从协程对象到事件循环

同步函数等待时占住调用线程。异步任务等待尚未完成的 Future 或 I/O 时,事件循环可以运行其他就绪任务。在同一线程交错运行也能实现并发。没有实际挂起的 await 可以直接继续。

调用 async def 定义的函数先得到协程对象,函数体此时还没运行。用 await 执行协程,或用 create_task 安排它由当前事件循环调度。Task 运行协程并保存结果,Future 则由其他代码完成。实验把 Future 交给回调设置结果,避免一直等待。

同步脚本可用 asyncio.run 启动顶层协程,它负责关闭事件循环。debug=True 开启调试,debug=None 尊重环境设置。在已有事件循环的线程内应直接 await。旧的 asyncio.coroutine 自 Python 3.11 移除,迁移为 async def 和 await。

循环从就绪回调继续执行任务。一个任务等待本机响应时,另一个已就绪的任务可以运行。响应到达后,等待任务重新进入可运行状态,随后从等待点继续。

同一个事件循环交错处理两条本机请求
本站示意图按实验的响应次序说明任务挂起与恢复。实际完成次序与 gather 的结果排列可不同。

实际请求与并发等待

对比实验只连接临时回环服务器。同步客户端逐条发请求,异步客户端可让多个请求先抵达,再等待服务器释放响应。先后关系由事件和请求路径核对,无需用固定秒数估算速度。

标准库用 start_server 监听临时端口,用 open_connection 打开 TCP 流,并在结束时关闭连接与服务器。可选 aiohttp 实验用一个 ClientSession,依次进入请求上下文、检查 HTTP 状态并读取文本。睡眠可演示等待,不代表实际 HTTP。

gather 接收协程或任务,正常结果依输入顺序返回。默认遇到异常会传播给等待者,其他任务可以继续。return_exceptions=True 把异常作为结果项。sleep 暂停当前任务,可通过 result 指定返回值。to_thread 可卸载阻塞式 I/O,也可传位置参数和关键字参数。

控制完成条件、取消和超时

asyncio.wait 接收 Task 或 Future 集合。3.11 起不能直接传协程。timeout 返回已完成和未完成集合,未完成任务继续存在。FIRST_COMPLETED 遇到第一个完成或取消即返回,FIRST_EXCEPTION 遇到异常即返回,ALL_COMPLETED 等全部完成或取消。

wait_for 到时会请求取消目标,并等待它处理取消,再抛出 TimeoutError。asyncio.TimeoutError 在 3.11 起是其别名。cancel 只是发出请求。清理后通常应继续抛出 CancelledError,done 为真表示任务有结果、异常或已取消。

result 在任务未完成时抛 InvalidStateError,正常结束返回值,失败时重抛异常。shield 可在调用者取消时让被保护的任务继续,调用者仍会收到 CancelledError,应保留被保护任务的引用并明确收尾。

current_task 用来查看正在执行的任务,all_tasks 列出尚未完成的任务。要管理多个长期任务,可用 TaskGroup 明确共同生命周期和出错收尾。

安排回调、同步数据与子进程

底层场景可自建事件循环。run_until_complete 等待任务结果,run_forever 运行到 stop,close 只在循环停下后调用。call_soon 安排下一轮回调,call_later 按延迟安排。跨线程提交回调应选 call_soon_threadsafe。

Lock、Event、Semaphore 用于同一事件循环内的异步协调,不能拿它们保护跨线程数据。asyncio.Queue 支持容量限制,每个已取任务完成后调用 task_done。生产结束后放入结束标记,再等待消费者退出,可避免无限等待。

用 create_subprocess_exec 直接给出程序和参数,以 communicate 收集标准输出和退出状态。实验启动当前 Python 执行一段固定命令。网络、文件、数据库和实时消息是否适合 asyncio,取决于客户端能否让出事件循环。普通同步文件调用可放到 to_thread。

下载并运行本站实验

解压运行 python python-asyncio.py。默认仅用标准库。装有 aiohttp 时可加 --aiohttp 复跑客户端练习。实验只访问本机,固定样本用来验证可观察顺序、异常和清理。

下载本站 asyncio 实验 ZIP

所需环境:CPython 3.12,aiohttp 可选

ZIP SHA256:b1342887b2e5c252a0c1557c0d97886c65d48d2e5db3a69071a24255d6969850

高级入口

接口与参数作用和条件
asyncio.run(coro, *, debug=None, loop_factory=None)运行顶层协程,关闭循环。debug=None 保留全局调试设置。
asyncio.create_task(coro, *, name=None, context=None)在运行中的循环安排协程。name 命名任务,context 可指定上下文。
asyncio.gather(*aws, return_exceptions=False)结果按输入排序,默认传播首个异常,也可将异常作为结果返回。
asyncio.sleep(delay, result=None)让出当前任务,等待后返回 result。
asyncio.wait(aws, *, timeout=None, return_when=ALL_COMPLETED)等待 Task 或 Future,返回 done、pending 集合,超时不自动取消。
asyncio.to_thread(func, /, *args, **kwargs)在工作线程调用同步函数并传递参数,等待其结果。

基本函数

接口与参数作用和条件
asyncio.run(coro)执行协程并管理顶层运行的事件循环。
asyncio.create_task(coro)把协程调度为 Task,可通过 await 收集结果。
asyncio.gather(*aws)并发等待,正常结果的排列跟随输入顺序。
asyncio.sleep(delay)暂停当前任务,让其他任务可以运行。
asyncio.wait(tasks_or_futures)3.11 起不直接接受协程对象。等待条件可选首个完成、首个异常或全部完成。

事件循环

接口与参数作用和条件
loop.run_until_complete(future)运行循环直到 Future 或协程完成,返回结果或抛出异常。
loop.run_forever()运行事件循环直到 stop 请求生效。
loop.stop()请求停止事件循环,当前批次回调可继续。
loop.close()释放事件循环资源,必须先停止循环。
loop.call_soon(callback, *args)把回调加入就绪队列,可传位置参数。
loop.call_later(delay, callback, *args)按单调时钟安排一次延迟回调。

协程与任务

接口与参数作用和条件
@asyncio.coroutine → async def旧生成器式装饰器自 3.11 移除,迁移为原生协程。
async def定义原生协程函数,调用得到协程对象。
Task.cancel()请求取消,任务在适当时机收到 CancelledError。
Task.done()正常返回、抛出异常或取消之后均为真。
Task.result()正常返回值或重抛异常。未完成时抛 InvalidStateError。

同步原语

接口与参数作用和条件
asyncio.Lock()串行访问同一循环内的临界区。
asyncio.Event()用事件标志通知等待的任务。
asyncio.Queue(maxsize=0)在任务之间传递数据,设置正容量后可阻塞 put。
asyncio.Semaphore(value=1)限制同时进入的任务数,释放后另一任务可进入。

网络与子进程

接口与参数作用和条件
asyncio.open_connection(host, port, …)建立连接,返回读写流。
asyncio.start_server(client_connected_cb, host, port, …)监听地址并为每个连接调用处理函数。
asyncio.create_subprocess_exec(program, *args, …)直接启动程序和参数,按需捕获流及退出状态。

诊断与控制

接口与参数作用和条件
asyncio.current_task(loop=None)返回当前正在运行的任务对象。
asyncio.all_tasks(loop=None)返回尚未完成的任务集合。
asyncio.shield(aw)隔离外层取消传播,外层仍收到 CancelledError。
asyncio.wait_for(aw, timeout)限时等待,到时请求取消目标并抛 TimeoutError。

本章自编源码与运行范围

Python · 阅读源码
"""Bounded asyncio exercises using only local processes and loopback connections."""
import argparse
import asyncio
from contextvars import ContextVar, copy_context
import inspect
import json
import os
from pathlib import Path
import subprocess
import sys
import threading
from urllib.request import ProxyHandler, build_opener


class Checks:
    def __init__(self):
        self.records = []

    def add(self, name, actual, expected, inputs, operation):
        if actual != expected:
            raise AssertionError((name, actual, expected))
        self.records.append(dict(name=name, actual=actual, expected=expected, inputs=inputs,
                                 operation=operation, passed=True))


async def task_basics(check):
    states = []

    async def compute():
        states.append('entered')
        return 8

    pending = compute()
    before = [inspect.iscoroutine(pending), list(states), hasattr(asyncio,'coroutine')]
    value = await pending
    check('native coroutine starts only when awaited', [before, states, value],
          [[True, [], sys.version_info < (3,11)], ['entered'], 8], 'async def compute',
          'Inspect coroutine object and state before and after awaiting it')

    loop = asyncio.get_running_loop()
    future = loop.create_future()
    before = future.done()
    loop.call_soon(future.set_result,'released')
    check('Future completes through explicit callback',[before,await future,future.done()],
          [False,'released',True],'pending Future with a scheduled producer','Await a Future that receives a value')

    label = ContextVar('label',default='default')
    context = copy_context()
    context.run(label.set,'dispatch')

    async def task_value():
        return [asyncio.current_task().get_name(),label.get()]

    task = asyncio.create_task(task_value(),name='loader',context=context)
    before = task in asyncio.all_tasks()
    result = await task
    check('create_task name and context',result,['loader','dispatch'],'explicit task name and context',
          'Read name and ContextVar from the started task')
    check('current_task and all_tasks show live task',
          [before,task in asyncio.all_tasks(),asyncio.current_task() in asyncio.all_tasks()],
          [True,False,True],'one current task and one child','Compare live task listings before and after completion')

    order = []
    loop.call_soon(order.append,'callback')
    output = await asyncio.sleep(0,result='resumed')
    check('sleep yields and returns value',[order,output],[['callback'],'resumed'],
          'queued callback and sleep(0)','Yield to the event loop and collect a result')

    gate = asyncio.Event()
    cleaned = asyncio.Event()

    async def wait_clean():
        try:
            await gate.wait()
        finally:
            cleaned.set()

    started = asyncio.create_task(wait_clean())
    await asyncio.sleep(0)
    try:
        started.result()
    except asyncio.InvalidStateError:
        pending_error = True
    else:
        pending_error = False
    normal = [task.done(),task.result()]
    check('task result and done states',[started.done(),pending_error,normal],[False,True,[True,['loader','dispatch']]],
          'an unfinished task and a completed task','Read status and request result in both states')
    requested = started.cancel()
    try:
        await started
    except asyncio.CancelledError:
        cancelled = True
    else:
        cancelled = False
    check('cancellation delivers exception and cleanup',[requested,cancelled,cleaned.is_set(),started.done()],
          [True,True,True,True],'cancel a started task at Event.wait','Observe CancelledError and run finally')

    cleaned.clear()
    try:
        await asyncio.wait_for(wait_clean(),.01)
    except TimeoutError:
        timed_out = True
    else:
        timed_out = False
    check('wait_for cancels target and runs cleanup',[timed_out,cleaned.is_set(),asyncio.TimeoutError is TimeoutError],
          [True,True,True],'unsignaled Event with bounded deadline','Await timeout, check cleanup and the 3.12 exception alias')

    inner = asyncio.create_task(gate.wait())

    async def outer():
        return await asyncio.shield(inner)

    wrapper = asyncio.create_task(outer())
    await asyncio.sleep(0)
    wrapper.cancel()
    try:
        await wrapper
    except asyncio.CancelledError:
        shielded = not inner.done()
    else:
        shielded = False
    gate.set()
    check('shield keeps inner task alive',[shielded,await inner],[True,True],
          'shielded inner and cancelled outer task','Observe outer cancellation, then complete and await inner')


async def waiting_modes(check):
    release = asyncio.Event()

    async def fail():
        raise ValueError('synthetic')

    delayed = asyncio.create_task(release.wait())
    try:
        done,pending = await asyncio.wait([delayed],timeout=0)
        check('wait timeout leaves tasks pending',[len(done),delayed in pending,delayed.cancelled()],
              [0,True,False],'unsignaled task with timeout=0','Inspect sets without cancelling the pending task')
        quick = asyncio.create_task(asyncio.sleep(0,result=4))
        done,pending = await asyncio.wait([quick,delayed],return_when=asyncio.FIRST_COMPLETED)
        first = [quick in done,delayed in pending]
        failed = asyncio.create_task(fail())
        done,pending = await asyncio.wait([failed,delayed],return_when=asyncio.FIRST_EXCEPTION)
        first_error = [isinstance(failed.exception(),ValueError),delayed in pending]
        direct = asyncio.sleep(0)
        try:
            await asyncio.wait([direct])
        except TypeError:
            refused = True
        else:
            refused = False
        finally:
            direct.close()
        release.set()
        done,pending = await asyncio.wait([delayed,quick],return_when=asyncio.ALL_COMPLETED)
        check('wait rejects coroutine and supports three modes',
              [refused,first,first_error,len(done),len(pending)],[True,[True,True],[True,True],2,0],
              'one delayed, one completed and one failed task plus a bare coroutine','Compare all wait predicates and validate 3.12 inputs')
    finally:
        release.set()
        await delayed

    release.clear()
    sibling = asyncio.create_task(release.wait())
    try:
        await asyncio.gather(fail(),sibling)
    except ValueError:
        error_seen = True
    else:
        error_seen = False
    survived = not sibling.done()
    release.set()
    await sibling
    results = await asyncio.gather(asyncio.sleep(0,result=7),fail(),return_exceptions=True)
    check('gather raises or collects exceptions',[error_seen,survived,results[0],type(results[1]).__name__],
          [True,True,7,'ValueError'],'one failing coroutine and one continuing sibling','Compare default propagation with return_exceptions=True')


async def synchronization(check):
    lock = asyncio.Lock()
    stock = 0

    async def add_stock():
        nonlocal stock
        async with lock:
            before = stock
            await asyncio.sleep(0)
            stock = before+1

    await asyncio.gather(*(add_stock() for _ in range(6)))
    check('async Lock preserves shared updates',stock,6,'six tasks with a forced scheduling point',
          'Hold the lock across reading, yielding and writing')

    signal = asyncio.Event()
    waiter = asyncio.create_task(signal.wait())
    await asyncio.sleep(0)
    suspended = not waiter.done()
    signal.set()
    awakened = await waiter
    signal.clear()
    check('async Event wakes and clears',[suspended,awakened,signal.is_set()],[True,True,False],
          'one waiter and an unset event','Suspend, signal and clear the event')

    work = asyncio.Queue(maxsize=1)
    stop = object()
    await work.put(2)
    next_item = asyncio.create_task(work.put(5))
    await asyncio.sleep(0)
    delayed = not next_item.done()
    results = []

    async def consume():
        while True:
            item = await work.get()
            try:
                if item is stop:
                    return
                results.append(item)
            finally:
                work.task_done()

    consumer = asyncio.create_task(consume())
    await next_item
    await work.put(stop)
    await work.join()
    await consumer
    check('async Queue accounts for data and stop token',[delayed,results,consumer.done()],
          [True,[2,5],True],'capacity one, two values and a stop token','Observe a blocked put, account for items and stop')

    limiter = asyncio.Semaphore(2)
    gate = asyncio.Event()
    two_inside = asyncio.Event()
    active = maximum = 0

    async def enter():
        nonlocal active,maximum
        async with limiter:
            active += 1
            maximum = max(maximum,active)
            if active==2:
                two_inside.set()
            await gate.wait()
            active -= 1

    tasks = [asyncio.create_task(enter()) for _ in range(4)]
    await two_inside.wait()
    blocked = sum(task.done() for task in tasks)
    gate.set()
    await asyncio.gather(*tasks)
    check('async Semaphore bounds concurrency',[blocked,maximum,active],[0,2,0],
          'four entrants, two permits','Hold the first entrants, then release and inspect the maximum')


async def local_http(check, aiohttp_enabled):
    arrivals = []
    both = asyncio.Event()
    first_sent = asyncio.Event()
    active = set()

    async def serve(reader, writer):
        task = asyncio.current_task()
        active.add(task)
        try:
            header = await reader.readuntil(b'\r\n\r\n')
            path = header.split(b' ')[1].decode('ascii')
            arrivals.append(path)
            if path=='/fast':
                both.set()
                await first_sent.wait()
            if path=='/slow':
                await both.wait()
            body = ('reply '+path).encode('ascii')
            writer.write(b'HTTP/1.1 200 OK\r\nContent-Length: '+str(len(body)).encode('ascii')
                         +b'\r\nConnection: close\r\n\r\n'+body)
            await writer.drain()
        finally:
            writer.close()
            await writer.wait_closed()
            active.discard(task)

    async with await asyncio.start_server(serve,'127.0.0.1',0) as server:
        port = server.sockets[0].getsockname()[1]

        def sync_reads():
            opener = build_opener(ProxyHandler({}))
            answers = []
            for path in ('/serial-a','/serial-b'):
                with opener.open(f'http://127.0.0.1:{port}{path}',timeout=3) as response:
                    answers.append(response.read().decode('ascii'))
            return answers

        serial = await asyncio.to_thread(sync_reads)
        check('blocking HTTP client reads serially',[arrivals[:],serial],
              [['/serial-a','/serial-b'],['reply /serial-a','reply /serial-b']],
              ['/serial-a','/serial-b'],'Read each real local HTTP response before sending the next request')
        arrivals.clear()
        finished = []

        async def request(path):
            reader,writer = await asyncio.open_connection('127.0.0.1',port)
            try:
                writer.write(f'GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n'.encode('ascii'))
                await writer.drain()
                head = await reader.readuntil(b'\r\n\r\n')
                body = (await reader.read()).decode('ascii')
                finished.append(path)
                if path=='/slow':
                    first_sent.set()
                return [head.split(b'\r\n',1)[0].decode('ascii'),body]
            finally:
                writer.close()
                await writer.wait_closed()

        tasks = [asyncio.create_task(request(p)) for p in ('/fast','/slow')]
        results = await asyncio.gather(*tasks)
        check('local HTTP overlaps while results retain input order',[sorted(arrivals),finished,results],
              [['/fast','/slow'],['/slow','/fast'],[['HTTP/1.1 200 OK','reply /fast'],['HTTP/1.1 200 OK','reply /slow']]],
              ['/fast','/slow'],'Require both requests before releasing either response and enforce reversed completion')

        if aiohttp_enabled:
            import aiohttp

            async def fetch(session,path):
                async with session.get(f'http://127.0.0.1:{port}{path}') as response:
                    response.raise_for_status()
                    return [response.status,await response.text()]

            async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=3),trust_env=False) as session:
                gathered = await asyncio.gather(fetch(session,'/session-a'),fetch(session,'/session-b'))
            check('aiohttp session fetches real local responses',[gathered,session.closed],
                  [[[200,'reply /session-a'],[200,'reply /session-b']],True],
                  ['/session-a','/session-b'],'Reuse one session, await real responses, then close it')

        if active:
            await asyncio.gather(*list(active))


async def services(check, aiohttp_enabled):
    await task_basics(check)
    await waiting_modes(check)
    await synchronization(check)
    await local_http(check,aiohttp_enabled)
    loop = asyncio.get_running_loop()
    main_thread = threading.get_ident()
    begun = asyncio.Event()
    proceed = threading.Event()

    def blocking(a, *, increment):
        loop.call_soon_threadsafe(begun.set)
        if not proceed.wait(4):
            raise RuntimeError('work was not released')
        return [a+increment,threading.get_ident()!=main_thread]

    background = asyncio.create_task(asyncio.to_thread(blocking,5,increment=2))
    await begun.wait()
    concurrent = not background.done()
    proceed.set()
    check('to_thread forwards args without blocking loop',[concurrent,await background],
          [True,[7,True]],'blocking synchronous callable with kwargs','Wait on the event loop while another thread waits on a signal')

    proc = await asyncio.create_subprocess_exec(sys.executable,'-I','-c','print(17*3)',
                                               stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE)
    stdout,stderr = await proc.communicate()
    check('async subprocess returns actual output',[stdout.decode().strip(),stderr.decode(),proc.returncode],
          ['51','',0],'current Python executable and fixed argument list','Collect actual subprocess streams and exit status')


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--aiohttp',action='store_true')
    parser.add_argument('--local-aiohttp-site',type=Path)
    options = parser.parse_args()
    if options.local_aiohttp_site:
        sys.path.insert(0,str(options.local_aiohttp_site.resolve(strict=True)))
    aiohttp_enabled = options.aiohttp or bool(options.local_aiohttp_site)
    if aiohttp_enabled:
        import aiohttp  # Import before starting the event loop.
    check = Checks()
    holder = {}

    async def run_entry():
        holder['loop'] = asyncio.get_running_loop()
        await asyncio.wait_for(services(check.add,aiohttp_enabled),20)
        return holder['loop'].get_debug()

    debug = asyncio.run(run_entry(),debug=True)
    check.add('run debug flag and closes loop',[debug,holder['loop'].is_closed()],[True,True],
              'asyncio.run(debug=True)','Inspect the running flag and closed loop state')
    env = dict(os.environ, PYTHONASYNCIODEBUG='1')
    debug_probe = (
        "import asyncio\n"
        "async def probe():\n return asyncio.get_running_loop().get_debug()\n"
        "print(asyncio.run(probe(), debug=None))"
    )
    debug_child = subprocess.run([sys.executable,'-B','-s','-X','utf8','-c',debug_probe],
                                 env=env,capture_output=True,text=True,check=True,timeout=8)
    check.add('run debug None reads environment',[debug_child.stdout.strip(),debug_child.stderr],['True',''],
              'PYTHONASYNCIODEBUG=1 in a subprocess that reads environment variables','Use default debug selection')
    loop = asyncio.new_event_loop()
    try:
        future = loop.create_future()
        loop.call_soon(future.set_result,'ok')
        check.add('low-level loop completes future',loop.run_until_complete(future),'ok',
                  'Future completed by call_soon','Run until the scheduled result arrives')
        observed = []
        loop.call_soon(observed.append,'ready')

        def end(label):
            observed.append(label)
            loop.stop()

        loop.call_later(.01,end,'timer')
        loop.run_forever()
    finally:
        loop.close()
    check.add('low-level loop callbacks stop and close',[observed,loop.is_closed()],[['ready','timer'],True],
              'call_soon then call_later','Run callbacks, stop the loop and close it')
    print(json.dumps(check.records,ensure_ascii=False))


if __name__ == '__main__':
    main()
运行本章核心实例

所需环境:Windows CPython 3.12, real loopback HTTP/streams, isolated subprocess and asyncio synchronization

当前源码 SHA256:8e729307ed8ceb13fad2470a0a5cb69cb585ef315533a0aa365b7be7821781a5

下载本站示例源码

当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。

常见错误与边界

  • 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。

练习与解答

使用本站实例修改一个条件,先写下预期,再实际运行。

展开参考解答

比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。

规范与官方依据