Skip to content

Instantly share code, notes, and snippets.

@fabiocerqueira
Created October 7, 2020 13:17
Show Gist options
  • Save fabiocerqueira/45610ae692fb29dacb17ab5f69d4985a to your computer and use it in GitHub Desktop.
Save fabiocerqueira/45610ae692fb29dacb17ab5f69d4985a to your computer and use it in GitHub Desktop.
Difference between blocking and non-blocking tasks in python
import time
import asyncio
async def my_blocking_task(task_id):
print(f"running blocking {task_id}")
time.sleep(2) # faking cpu task
async def my_nonblocking_task(task_id):
print(f"running nonblocking {task_id}")
await asyncio.sleep(2)
async def run_all(my_task):
loop = asyncio.get_running_loop()
tasks = [loop.create_task(my_task(task_id)) for task_id in range(3)]
await asyncio.gather(*tasks)
if __name__ == "__main__":
start = time.time()
asyncio.run(run_all(my_blocking_task))
end = time.time()
print(f"Blocking: {end - start}s")
start = time.time()
asyncio.run(run_all(my_nonblocking_task))
end = time.time()
print(f"NonBlocking: {end - start}s")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment