import asyncio
from asyncio import Lock, Queue
cache = {}
lock = Lock()
async def get_stuff(url):
# lock.acquire()是一个协程
# await lock.acquire()
# with await lock
# Lock实现了__enter__和__exit__可以使用with语法
async with lock:
if url in cache:
return cache[url]
stuff = await aiohttp.request('GET', url)
cache[url] = stuff
return stuff
async def parse_stuff():
stuff = await get_stuff()
# do some parsing
async def use_stuff():
stuff = await get_stuff()
# use stuff to do something interesting
if __name__ == '__main__':
tasks = [parse_stuff(), use_stuff()]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
Python 高级编程和异步IO并发编程 --13_8 asyncio的同步和通信
猜你喜欢
转载自blog.csdn.net/f2157120/article/details/105402001
今日推荐
周排行