asyncio中如何控制并发度?

进阶

答题要点

import asyncio
from asyncio import Semaphore, BoundedSemaphore

# Semaphore限制并发
async def fetch_with_limit(url: str, semaphore: Semaphore):
    async with semaphore:
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as response:
                return await response.json()

async def fetch_all(urls: list, max_concurrent: int = 10):
    semaphore = Semaphore(max_concurrent)
    tasks = [fetch_with_limit(url, semaphore) for url in urls]
    return await asyncio.gather(*tasks)

# 使用asyncio.Queue控制
async def worker(name: str, queue: asyncio.Queue):
    while True:
        item = await queue.get()
        try:
            await process(item)
        finally:
            queue.task_done()

async def main():
    queue = asyncio.Queue()
    # 启动固定数量的worker
    workers = [asyncio.create_task(worker(f'worker-{i}', queue))
               for i in range(10)]

    # 添加任务
    for item in items:
        await queue.put(item)

    # 等待完成
    await queue.join()

    # 取消workers
    for w in workers:
        w.cancel()

# 批量处理
async def process_in_batches(items, batch_size=100, concurrency=10):
    semaphore = Semaphore(concurrency)

    async def process_batch(batch):
        async with semaphore:
            return await asyncio.gather(*[process(item) for item in batch])

    results = []
    for i in range(0, len(items), batch_size):
        batch = items[i:i+batch_size]
        batch_results = await process_batch(batch)
        results.extend(batch_results)
    return results

# 动态并发控制
class AdaptiveConcurrencyLimiter:
    def __init__(self, initial=10, min_limit=1, max_limit=100):
        self.limit = initial
        self.min_limit = min_limit
        self.max_limit = max_limit
        self.semaphore = Semaphore(initial)
        self.success_count = 0
        self.failure_count = 0

    async def acquire(self):
        await self.semaphore.acquire()

    def release(self, success: bool):
        self.semaphore.release()
        if success:
            self.success_count += 1
        else:
            self.failure_count += 1
        self._adjust()

    def _adjust(self):
        total = self.success_count + self.failure_count
        if total >= 100:
            failure_rate = self.failure_count / total
            if failure_rate > 0.1 and self.limit > self.min_limit:
                self.limit = max(self.limit - 1, self.min_limit)
            elif failure_rate < 0.01 and self.limit < self.max_limit:
                self.limit = min(self.limit + 1, self.max_limit)
            self.success_count = 0
            self.failure_count = 0

完整解析在题库里看

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

去练这道题