Skip to content

Instantly share code, notes, and snippets.

@nngogol
Created May 7, 2020 14:19
Show Gist options
  • Save nngogol/74f3689b9b87fd14a1760b6f0bb7b8cf to your computer and use it in GitHub Desktop.
Save nngogol/74f3689b9b87fd14a1760b6f0bb7b8cf to your computer and use it in GitHub Desktop.
(async)Racing show in less then 50 lines
'''
Made at 2020-05-07 15:31:52
Asyncio Racing Show
run with:
$ clear; python3 -uB comp.py
'''
import asyncio, random, queue
failed_runners = queue.Queue()
flag = False
async def runner(name):
global flag, failed_runners
for i in range(5):
await asyncio.sleep(random.randint(1,2)/100)
if not flag: # if nobody grabbed the flag -> I won.
flag = f' Mister {name}'
print(f' flag is taken by Mr.{name}\n')
else: # if flag is gone -> I failed.
failed_runners.put(f'Finished, but failed "Mr.{name}"')
async def checker():
global flag, failed_runners
print('START of COMPETITION')
while not flag:
await asyncio.sleep(.001) # let's wait for flag state more
# show failers
if not failed_runners.empty():
print (' list of failers:')
while not failed_runners.empty():
item = failed_runners.get()
if item is not None: print(f' >>> {item}')
else: break
# show winner
print(' ', '-'*30, f'\n WINNER is {flag.strip()}! Congrats!')
print('\nEND OF COMPETITION')
print('global START\n')
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(*[runner(i) for i in range(60)], checker()))
loop.close()
print('\nglobal END')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment