【12.7】asyncio的同步和通信

雨燕双飞 提交于 2019-11-28 01:41:09
 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))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!