了解 Python 与 Asyncio 的并发

Understanding Python Concurrency with Asyncio

我想知道 python 3.6 中并发是如何使用 asyncio 的。我的理解是,当解释器执行 await 语句时,它会把它留在那里,直到等待过程完成,然后继续执行另一个协程任务。但是我在下面的代码中看到的不是那样。程序同步运行,一个任务一个任务执行。

我的理解和实现代码有什么问题?


    import asyncio
    import time

    async def myWorker(lock, i):
        print("Attempting to attain lock {}".format(i))
        # acquire lock
        with await lock:
            # run critical section of code
            print("Currently Locked")

            time.sleep(10)

        # our worker releases lock at this point
        print("Unlocked Critical Section")

    async def main():
        # instantiate our lock
        lock = asyncio.Lock()
        # await the execution of 2 myWorker coroutines 
        # each with our same lock instance passed in 
        # await asyncio.wait([myWorker(lock), myWorker(lock)])
        tasks = []

        for i in range(0, 100):
            tasks.append(asyncio.ensure_future(myWorker(lock, i)))

        await asyncio.wait(tasks)


    # Start up a simple loop and run our main function
    # until it is complete
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    print("All Tasks Completed")
    loop.close()

在 asyncio 协程中调用 time.sleep 等阻塞调用会阻塞整个事件循环,违背了使用 asyncio 的目的。

time.sleep(10) 更改为 await asyncio.sleep(10),代码将按您预期的方式运行。

asyncio 使用循环来 运行 一切,await 会将控制权交还给循环,以便它可以将下一个协程安排到 运行。