Skip to content

Commit

Permalink
double check cache
Browse files Browse the repository at this point in the history
  • Loading branch information
aiudirog committed Oct 17, 2023
1 parent b11cc6d commit 73d7c01
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions aiuti/asyncio.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,15 +308,15 @@ def threadsafe_async_cache(
>>> import asyncio as aio
>>> @threadsafe_async_cache
... async def square(x: int):
... async def square(x: int) -> int:
... await aio.sleep(0.1)
... print("Squaring:", x)
... return x * x
Then we'll define a function that will use a new event loop to call
the function 10 times in parallel:
>>> async def square_10x(x: int):
>>> async def square_10x(x: int) -> List[int]:
... return await aio.gather(*(square(x) for _ in range(10)))
And finally we'll call that function 10 times in parallel across 10
Expand Down Expand Up @@ -410,6 +410,10 @@ async def _wrapper(*args: Any, **kwargs: Any) -> Any:
# caching the value
loop, event = events[key]
except KeyError:
try: # verify nothing cached while waiting for lock
return _cache[key]
except KeyError:
pass
# No existing event -> this task is going to cache
# the value and provide an event for others to wait
loop = aio.get_running_loop()
Expand Down

0 comments on commit 73d7c01

Please sign in to comment.