[Python] Why CPU bound task doesn't block asyncio event loop?

Discussão em 'Python' iniciado por Stack, Fevereiro 8, 2025.

  1. Stack

    Stack Membro Participativo

    I want to go deep in asynchronous task execution in python and I made experiment when CPU Bound task runs with IO bound task simultaneously.

    I suppose that CPU Bound task blocks the event loop and IO Bound task will start after CPU Bound task finished. But in my experiment I see that IO Bound task start and finishes simultaneously with CPU Bound. I want to find answer, why it happens.

    To make IO bound load I use asyncio.sleep, to make CPU bound load I use for loop with multiplying and division.

    Experiment code:

    import asyncio
    from datetime import datetime

    async def io_bound(i):
    print(f'start io_bound {i} {datetime.now().strftime("%H:%M:%S")}')
    await asyncio.sleep(1)
    print(f'finish io_bound {i} {datetime.now().strftime("%H:%M:%S")}')

    async def cpu_bound():
    print(f'start cpu_bound {datetime.now().strftime("%H:%M:%S")}')
    for i in range(5 * 10**7):
    i *= i+1
    i /= i+1
    print(f'finish cpu_bound {datetime.now().strftime("%H:%M:%S")}')

    async def main():
    await io_bound(1)
    asyncio.create_task(cpu_bound())
    await io_bound(2)

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(main())


    output:

    start io_bound 1 17:28:20
    finish io_bound 1 17:28:21
    start io_bound 2 17:28:21
    start cpu_bound 17:28:21
    finish cpu_bound 17:28:26
    finish io_bound 2 17:28:26


    I expected that output should be:

    start io_bound 1 17:28:20
    finish io_bound 1 17:28:21
    start io_bound 2 17:28:21
    start cpu_bound 17:28:21
    finish cpu_bound 17:28:26
    finish io_bound 2 17:28:27


    That is, io_bound task should finish one second after cpu_bound is finished.

    So the question is: Why io_bound finishes immediately after cpu_bound is finished? Doesn't CPU bound task block execution of other tasks?

    Thanks for any responses.

    Continue reading...

Compartilhe esta Página