Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.