Python asyncio task ordering

后端 未结 1 1690
孤街浪徒
孤街浪徒 2021-01-18 05:45

I have a question about how the event loop in python\'s asyncio module manages outstanding tasks. Consider the following code:

import asyncio

@         


        
相关标签:
1条回答
  • 2021-01-18 06:40

    Currently your example doesn't include any blocking I/O code. Try this to simulate some tasks:

    import asyncio
    
    
    @asyncio.coroutine
    def coro(tag, delay):
        for i in range(1, 8):
            print(tag, i)
            yield from asyncio.sleep(delay)
    
    
    loop = asyncio.get_event_loop()
    
    print("---- await 0 seconds :-) --- ")
    tasks = [
        asyncio.Task(coro("A", 0)),
        asyncio.Task(coro("B", 0)),
        asyncio.Task(coro("C", 0)),
    ]
    
    loop.run_until_complete(asyncio.wait(tasks))
    
    print("---- simulate some blocking I/O --- ")
    tasks = [
        asyncio.Task(coro("A", 0.1)),
        asyncio.Task(coro("B", 0.3)),
        asyncio.Task(coro("C", 0.5)),
    ]
    
    loop.run_until_complete(asyncio.wait(tasks))
    
    loop.close()
    

    As you can see, coroutines are scheduled as needed, and not in order.

    0 讨论(0)
提交回复
热议问题