Skip to content

Instantly share code, notes, and snippets.

@robagar
Created June 6, 2021 06:18
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 robagar/b8170be3482403ff5f13d697485aa0ad to your computer and use it in GitHub Desktop.
Save robagar/b8170be3482403ff5f13d697485aa0ad to your computer and use it in GitHub Desktop.
Asyncio concurrency with conditions
#!/usr/bin/env python3
import asyncio
from time import time
async def main():
async def counter():
i = 1
t0 = time()
while True:
t = time() - t0
print(f'[counter] {i} at t={t:0.2f}')
i += 1
await asyncio.sleep(0.25)
ticked = asyncio.Condition()
tocked = asyncio.Condition()
async def tick():
while True:
print('[tick] sleep')
await asyncio.sleep(1)
print('TICK')
print('[tick] acquire ticked')
await ticked.acquire()
print('[tick] notify ticked')
ticked.notify()
ticked.release()
async with tocked:
print('[tick] wait tocked')
await tocked.wait()
async def tock():
while True:
print('[tock] sleep')
await asyncio.sleep(1)
print('...TOCK')
print('[tock] acquire tocked')
await tocked.acquire()
print('[tock] notify tocked')
tocked.notify()
tocked.release()
async with ticked:
print('[tock] wait ticked')
await ticked.wait()
await asyncio.wait([
asyncio.create_task(counter()),
asyncio.create_task(tick()),
asyncio.create_task(tock())
])
asyncio.run(main())
# loop = asyncio.get_event_loop()
# loop.run_until_complete(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment