第十二章 asyncio并发编程

目录

13.1 协程嵌套

示例代码:

13.2 线程嵌套

示例代码:

13.3 call_soon, call_later, call_at, call_soon_threadsafe

示例代码:

13.4 ThreadPoolExecutor + asyncio

示例代码:

13.5 asyncio模拟HTTP请求

示例代码:

13.6 future和task

示例代码:

13.7 asyncio同步和通信

示例代码:

13.8 aiohttp实现高并发爬虫

示例代码:

13.9 本章小结


在现代应用程序开发中,高效的并发处理能力是关键需求之一。Python的asyncio库提供了强大的异步编程支持,使得编写高效的I/O密集型代码变得更加简单和直观。本章将深入探讨asyncio的并发编程,涵盖其核心概念和常见用法。

13.1 协程嵌套

协程嵌套是asyncio中一个重要的特性,它允许一个协程在运行过程中调用另一个协程。

示例代码:
import asyncio

async def nested():
    print("This is a nested coroutine")
    return 42

async def main():
    print("Running main coroutine")
    result = await nested()
    print(f"Result from nested: {result}")

asyncio.run(main())

13.2 线程嵌套

在某些情况下,我们需要在异步代码中使用阻塞的代码,这时可以使用asyncio提供的线程支持来嵌套执行阻塞操作。

示例代码:
import asyncio
import concurrent.futures

def blocking_io():
    print("Start blocking I/O operation")
    # 模拟阻塞操作
    import time
    time.sleep(3)
    print("End blocking I/O operation")
    return "Blocking I/O result"

async def main():
    loop = asyncio.get_running_loop()
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(pool, blocking_io)
        print(result)

asyncio.run(main())

13.3 call_soon, call_later, call_at, call_soon_threadsafe

asyncio提供了多个函数来调度回调函数的执行。

  • call_soon:尽快调用回调函数。
  • call_later:在指定的时间后调用回调函数。
  • call_at:在指定的绝对时间调用回调函数。
  • call_soon_threadsafe:线程安全地尽快调用回调函数。
示例代码:
import asyncio

def callback(name):
    print(f"Callback {name} called")

async def main():
    loop = asyncio.get_running_loop()
    loop.call_soon(callback, 'call_soon')
    loop.call_later(1, callback, 'call_later')
    loop.call_at(loop.time() + 2, callback, 'call_at')
    loop.call_soon_threadsafe(callback, 'call_soon_threadsafe')
    await asyncio.sleep(3)

asyncio.run(main())

13.4 ThreadPoolExecutor + asyncio

asyncioconcurrent.futures.ThreadPoolExecutor结合使用,可以在事件循环中运行阻塞的线程。

示例代码:
import asyncio
import concurrent.futures

def blocking_task():
    import time
    time.sleep(2)
    return "Result from blocking task"

async def main():
    loop = asyncio.get_running_loop()
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(pool, blocking_task)
        print(result)

asyncio.run(main())

13.5 asyncio模拟HTTP请求

使用asyncio模拟HTTP请求,可以高效地处理大量并发请求。

示例代码:
import asyncio
import aiohttp

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, 'http://example.com')
        print(html)

asyncio.run(main())

13.6 future和task

asyncio中的Future对象表示一个异步操作的结果,Task对象是一个负责执行协程的Future对象。

示例代码:
import asyncio

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    task1 = asyncio.create_task(say_after(1, 'hello'))
    task2 = asyncio.create_task(say_after(2, 'world'))

    print("Tasks created")
    await task1
    await task2

asyncio.run(main())

13.7 asyncio同步和通信

asyncio提供了多种同步和通信机制,包括队列、事件、锁和信号量。

示例代码:
import asyncio

async def producer(queue):
    for i in range(5):
        await asyncio.sleep(1)
        await queue.put(i)
        print(f"Produced {i}")

async def consumer(queue):
    while True:
        item = await queue.get()
        if item is None:
            break
        print(f"Consumed {item}")

async def main():
    queue = asyncio.Queue()
    producer_task = asyncio.create_task(producer(queue))
    consumer_task = asyncio.create_task(consumer(queue))

    await producer_task
    await queue.put(None)  # 用于终止消费者
    await consumer_task

asyncio.run(main())

13.8 aiohttp实现高并发爬虫

aiohttp是一个基于asyncio的异步HTTP客户端,可以用来实现高并发爬虫。

示例代码:
import asyncio
import aiohttp

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    urls = [
        'http://example.com',
        'http://example.org',
        'http://example.net',
    ]
    
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        results = await asyncio.gather(*tasks)
        
        for result in results:
            print(result)

asyncio.run(main())

13.9 本章小结

在本章中,我们详细探讨了asyncio并发编程,包括协程嵌套、线程嵌套、调度回调函数、结合ThreadPoolExecutor使用、模拟HTTP请求、FutureTask对象、同步和通信机制以及使用aiohttp实现高并发爬虫。通过这些内容,读者可以更深入地理解和掌握asyncio的高级用法,编写高效、可扩展的异步代码。如果您有任何进一步的问题或需要更详细的解释,请随时告诉我!

  • 15
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

湘大小菜鸡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值