并发:asyncio 中 Lock 使用

2020-07-31  本文已影响0人  dex0423
import asyncio
from asyncio import Lock
import aiohttp


cache = {}
lock = Lock()


async def get_stuff(url):
    # await lock.acquire()      #
    async with lock:
        if url in cache:
            return cache[url]
        stuff = await aiohttp.request("GET", url=url)
        cache[url] = stuff
        return stuff
    # lock.release()            # release 不用 await

async def func_1(url):
    """
    异步调用 get_stuff(url)
    :return:
    """
    stuff_1 = await get_url(url=url)
    return stuff_1


async def func_2(url):
    """
    异步调用 get_stuff(url)
    :return:
    """
    stuff_2 = await get_url(url=url)
    return stuff_2


url = "xxx"
tasks = [func_1(url), func_2(url)]    # 注意:
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))


上一篇下一篇

猜你喜欢

热点阅读