Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mgraczyk
Created August 1, 2020 05:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgraczyk/e251443bccfe54505e75b6526550c113 to your computer and use it in GitHub Desktop.
Save mgraczyk/e251443bccfe54505e75b6526550c113 to your computer and use it in GitHub Desktop.
import asyncio
num_times = 0
async def one_time_setup():
global num_times
num_times += 1
print("doing setup")
await asyncio.sleep(1)
D = {}
async def maybe_initialize():
global D
this_setup = asyncio.ensure_future(one_time_setup())
actual_setup = D.setdefault('initializer', this_setup)
if this_setup is not actual_setup:
print('canceling')
this_setup.cancel()
await actual_setup
return
async def main():
await asyncio.wait([
maybe_initialize(),
maybe_initialize(),
maybe_initialize(),
maybe_initialize(),
])
print(f'ran {num_times} times')
asyncio.run(main())
'''
# Output
$ python3 test.py
canceling
canceling
canceling
doing setup
ran 1 times
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment