目录
13.3 call_soon, call_later, call_at, call_soon_threadsafe
13.4 ThreadPoolExecutor + asyncio
在现代应用程序开发中,高效的并发处理能力是关键需求之一。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
asyncio
与concurrent.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请求、Future
和Task
对象、同步和通信机制以及使用aiohttp
实现高并发爬虫。通过这些内容,读者可以更深入地理解和掌握asyncio
的高级用法,编写高效、可扩展的异步代码。如果您有任何进一步的问题或需要更详细的解释,请随时告诉我!