1 import asyncio 2 from asyncio import Lock, Queue 3 cache = {} 4 lock = Lock() 5 6 7 async def get_stuff(url): 8 # lock.acquire()是一个协程 9 # await lock.acquire() 10 # with await lock 11 # Lock实现了__enter__和__exit__可以使用with语法 12 async with lock: 13 if url in cache: 14 return cache[url] 15 stuff = await aiohttp.request('GET', url) 16 cache[url] = stuff 17 return stuff 18 19 20 async def parse_stuff(): 21 stuff = await get_stuff() 22 # do some parsing 23 24 25 async def use_stuff(): 26 stuff = await get_stuff() 27 # use stuff to do something interesting 28 29 30 if __name__ == '__main__': 31 tasks = [parse_stuff(), use_stuff()] 32 loop = asyncio.get_event_loop() 33 loop.run_until_complete(asyncio.wait(tasks))