Skip to content

async

Asyncio Is Not Parallelism

Also posted at medium.com.
You may have heard that Python asyncio is concurrent but not parallel programming. But how? I will explain it with simple examples.

Let’s start with a perfect concurrent example #1

import asyncio
import time

async def say_after(delay, what):
    print(time.time(),'Start say_after(%s, %s)' % (delay,what))
    await asyncio.sleep(delay)
    print(time.time(),what)

async def main():
    start_time = time.time()
    print(start_time, 'Before creating tasks.')
    task1 = asyncio.create_task(say_after(1, 'hello'))
    task2 = asyncio.create_task(say_after(2, 'world'))    
    await task1
    await task2     
    end_time = time.time()
    print('Total time elapsed: %.2f seconds' % (end_time - start_time))

asyncio.run(main())