Tuesday, 14 January 2020

python asyncio

#run tasks one by one = synchronous

import asyncio
import time

async def task(num):

    print(f'start task {num}')
    await asyncio.sleep(1)
    i = 0
    while(i < 10000000):
        i += 1
    print(f'done task {num}')

async def main():
    print(f"started at {time.strftime('%X')}")

    await task(1)
    await task(2)
    await task(3)
    await task(4)
    await task(5)

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

----------------------------
#logs
#took 9 seconds to finish

started at 08:06:39
start task 1
done task 1
start task 2
done task 2
start task 3
done task 3
start task 4
done task 4
start task 5
done task 5
finished at 08:06:48

---------------------------
#run tasks concurrently = multiprocess

import asyncio
import time

#when current task is in idle, other tasks start to run
async def task(num):

    print(f'start task {num}')
    await asyncio.sleep(1)
    i = 0
    while(i < 10000000):
        i += 1
    print(f'done task {num}')

async def main():
    print(f"started at {time.strftime('%X')}")

    task1 = asyncio.create_task(task(1))
    task2 = asyncio.create_task(task(2))
    task3 = asyncio.create_task(task(3))
    task4 = asyncio.create_task(task(4))
    task5 = asyncio.create_task(task(5))

    await task1
    await task2
    await task3
    await task4
    await task5

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

-----------------------------
#logs
#finish in 5 seconds

started at 08:11:33
start task 1
start task 2
start task 3
start task 4
start task 5
done task 1
done task 3
done task 5
done task 2
done task 4
finished at 08:11:38

reference:
https://realpython.com/async-io-python/
https://docs.python.org/3/library/asyncio-task.html#coroutine

No comments:

Post a Comment