首页 > 其他 > 详细

【12.7】asyncio的同步和通信

时间:2019-08-21 01:52:25      阅读:126      评论:0      收藏:0      [点我收藏+]
 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))

【12.7】asyncio的同步和通信

原文:https://www.cnblogs.com/zydeboke/p/11386261.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!