[Python] is asyncio.to_thread() method different to ThreadPoolExecutor?

Discussão em 'Python' iniciado por Stack, Abril 21, 2025.

  1. Stack

    Stack Membro Participativo

    I see that asyncio.to_thread() method is been added @python 3.9+, its description says it runs blocking codes on a separate thread to run at once. see example below:

    def blocking_io():
    print(f"start blocking_io at {time.strftime('%X')}")
    # Note that time.sleep() can be replaced with any blocking
    # IO-bound operation, such as file operations.
    time.sleep(1)
    print(f"blocking_io complete at {time.strftime('%X')}")

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

    await asyncio.gather(
    asyncio.to_thread(blocking_io),
    asyncio.sleep(1))

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


    asyncio.run(main())

    # Expected output:
    #
    # started main at 19:50:53
    # start blocking_io at 19:50:53
    # blocking_io complete at 19:50:54
    # finished main at 19:50:54


    By explanation, it seems like using thread mechanism and not context switching nor coroutine. Does this mean it is not actually an async after all? is it same as a traditional multi-threading as in concurrent.futures.ThreadPoolExecutor? what is the benefit of using thread this way then?

    Continue reading...

Compartilhe esta Página