Understanding Python Concurrency with Asyncio

I was wondering how concurrency works in python 3.6 with asyncio. My understanding is that when the interpreter executing await statement, it will leave it there until the awaiting process is complete and then move on to execute the other coroutine task. But what I see here in the code below is not like that. The program runs synchronously, executing task one by one.

What is wrong with my understanding and my impletementation code?


    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()


Invoking a blocking call such as time.sleep in an asyncio coroutine blocks the whole event loop, defeating the purpose of using asyncio.

Change time.sleep(10) to await asyncio.sleep(10) , and the code will behave like you expect.


asyncio使用一个循环来运行一切, await会让控制回到循环,这样它可以安排下一个协程运行。

链接地址: http://www.djcxy.com/p/53220.html

上一篇: 从asyncio.Protocol.data调用协程

下一篇: 通过Asyncio了解Python并发