12.7asyncio的同步和通信
Posted zydeboke
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了12.7asyncio的同步和通信相关的知识,希望对你有一定的参考价值。
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.7asyncio的同步和通信的主要内容,如果未能解决你的问题,请参考以下文章