蓝色天空网mbsky.com · 知识 · 实践 · 创造Skills(技能) · 本地阅读预览
教程 / AI / 智能开发 / Skills(技能)

Skills 异步请求、文件等待与进程计算

根据等待和计算的性质选择同步、异步、线程或进程,观察真实请求重叠和任务取消。

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

学完这一章,你能够

先判断正在等待什么

单个短操作适合直接同步执行。asyncio 在事件循环上调度可等待任务,网络或文件操作让出控制权时可以继续别的任务。并发等待和多个 CPU 核同时执行是两种机制。

对普通 CPython 3.12 中的纯 Python CPU 工作,可用可序列化函数和 ProcessPoolExecutor。Windows 子进程需要可导入的主模块与入口保护。本站实测子进程计算给定范围内的素数数目。

用实际服务看并发重叠和结果

复用一个 aiohttp ClientSession,用信号量限制同时发出的请求数。gather 按输入顺序给出结果。为每个请求设置超时,逐条处理 HTTP、传输和 JSON 错误,保证其他成功项仍可检查。

本站回环服务为三个成功接口各加了一段等待。两种调度读取相同业务值,服务记录实际在途数量。整体等待受最慢请求、并发上限、连接和服务处理影响,远程吞吐需单独测量。

读取文件并取消不再需要的任务

aiofiles 将常见阻塞文件操作委托给线程池。本站读取两个 UTF-8 文件,同时让缺文件返回带文件名的状态。行数按 splitlines 计算,末行没有换行符时仍计一行。

先安排快慢任务,再分别使用 wait_for 设超时。超时后被等待任务收到 CancelledError,做好清理后应继续传递。等待取消清理可能使调用总时长超过名义超时。实测慢任务未返回业务结果,快任务正常完成。

不同任务的执行选择

条目用途与条件
简单同步路径单次读写或请求采用直观顺序。
异步 I/O按服务条件限制并发,验证重叠与逐请求结果。
线程池委托使用 aiofiles,并检查文件内容、顺序和异常。
独立进程显示实际工作进程与已知计算结果。

观察并发 I/O、任务取消和进程计算

python · 阅读源码
"""Compare concurrent HTTP waits, local file I/O and a process pool."""
import argparse
import asyncio
from concurrent.futures import ProcessPoolExecutor
import json
from math import isqrt
from pathlib import Path
import os
from time import perf_counter
from urllib.parse import urlsplit

import aiofiles
import aiohttp


async def fetch(session,origin,route,gate):
    async with gate:
        try:
            async with session.post(origin+route,json={"batches":2},allow_redirects=False) as response:
                if response.status!=200:
                    return {"route":route,"code":"HTTP","http":response.status}
                data=await response.json()
                if not isinstance(data,dict) or type(data.get("units")) is not int:
                    return {"route":route,"code":"SCHEMA"}
                return {"route":route,"units":data["units"]}
        except TimeoutError:
            return {"route":route,"code":"TIMEOUT"}
        except (aiohttp.ClientError,ValueError):
            return {"route":route,"code":"TRANSPORT_OR_DATA"}


async def http_batch(origin,routes,workers,serial,timeout):
    parts=urlsplit(origin)
    if parts.scheme!="http" or parts.hostname!="127.0.0.1" or not parts.port or parts.username or parts.password or parts.path or parts.query or parts.fragment:
        raise ValueError("expected an explicit loopback HTTP origin")
    allowed={"/estimate","/count","/labels","/failed","/bad","/slow"}
    if any(route not in allowed for route in routes):
        raise ValueError("unknown fixture route")
    gate=asyncio.Semaphore(workers)
    started=perf_counter()
    async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=timeout),trust_env=False) as session:
        if serial:
            values=[await fetch(session,origin,route,gate) for route in routes]
        else:
            values=await asyncio.gather(*(fetch(session,origin,route,gate) for route in routes))
    return {"results":values,"seconds":perf_counter()-started}


async def read_one(path):
    try:
        async with aiofiles.open(path,mode="r",encoding="utf-8") as handle:
            text=await handle.read()
        return {"file":path.name,"chars":len(text),"lines":len(text.splitlines())}
    except FileNotFoundError:
        return {"file":path.name,"code":"MISSING"}
    except (OSError,UnicodeError):
        return {"file":path.name,"code":"READ_ERROR"}


async def read_batch(paths):
    return await asyncio.gather(*(read_one(path) for path in paths))


async def deadline_demo():
    cancelled=[]
    completed=[]
    async def job(name,delay):
        try:
            await asyncio.sleep(delay)
            completed.append(name)
            return name
        except asyncio.CancelledError:
            cancelled.append(name)
            raise
    async def bounded(name,delay):
        try:
            return {"name":name,"result":await asyncio.wait_for(job(name,delay),timeout=.12)}
        except TimeoutError:
            return {"name":name,"code":"TIMEOUT"}
    results=await asyncio.gather(bounded("quick",.025),bounded("slow",.4))
    return {"results":results,"cancelled":cancelled,"completed":completed}


def primes(limit):
    found=sum(all(value%divisor for divisor in range(2,isqrt(value)+1)) for value in range(2,limit))
    return {"limit":limit,"count":found,"pid":os.getpid()}


def cpu_work(limits):
    with ProcessPoolExecutor(max_workers=2) as pool:
        return {"parent":os.getpid(),"items":list(pool.map(primes,limits))}


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    commands=parser.add_subparsers(dest="kind",required=True)
    http=commands.add_parser("http")
    http.add_argument("origin")
    http.add_argument("routes",nargs="+")
    http.add_argument("--workers",type=int,default=3)
    http.add_argument("--timeout",type=float,default=2)
    http.add_argument("--serial",action="store_true")
    files=commands.add_parser("files")
    files.add_argument("paths",nargs="+",type=Path)
    commands.add_parser("deadlines")
    commands.add_parser("primes")
    args=parser.parse_args()
    if args.kind=="http":
        if args.workers<1 or args.timeout<=0:
            parser.error("positive workers and timeout are required")
        result=asyncio.run(http_batch(args.origin,args.routes,args.workers,args.serial,args.timeout))
    elif args.kind=="files":
        result=asyncio.run(read_batch(args.paths))
    elif args.kind=="deadlines":
        result=asyncio.run(deadline_demo())
    else:
        result=cpu_work((1000,2000))
    print(json.dumps(result,ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 向本地服务顺序及并发发送同一组请求,结果逐项一致,服务器观察到并发请求重叠。另运行 UTF-8 文件读取、快慢任务和子进程素数统计。
观察并发 I/O、任务取消和进程计算

所需环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。

当前源码 SHA256:ff662ed7b06b83f46123699847bb9e383cefcbf4098a6ac9804e66f1284ef513

下载本站示例源码

运行本地实验

解压后按 README 运行当前章节对应的脚本,并查看真实输出。

下载 Skills 基础实验

所需环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。

ZIP SHA256:a8ff3b3322846a79aab618e7be813592d1fe214cb6551fc908ff99fd8a82cc4b

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

并发启动任务后为什么还要设置上限?

展开参考解答

连接、服务端容量和本机资源都有限,按允许额度控制并行等待,单个失败也要有独立结果。

规范与官方依据