Created
August 1, 2020 05:51
-
-
Save mgraczyk/e251443bccfe54505e75b6526550c113 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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