简体   繁体   English

了解Asyncio的Python并发性

[英]Understanding Python Concurrency with Asyncio

I was wondering how concurrency works in python 3.6 with asyncio. 我想知道并发如何在带有异步的python 3.6中工作。 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. 我的理解是,当解释器执行await语句时,它将留在那里,直到等待过程完成,然后继续执行其他协程任务。 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. 调用阻塞调用诸如time.sleep在协程ASYNCIO块整个事件循环,击败使用ASYNCIO的目的。

Change time.sleep(10) to await asyncio.sleep(10) , and the code will behave like you expect. 更改await asyncio.sleep(10) time.sleep(10)await asyncio.sleep(10) ,代码将像您期望的那样运行。

asyncio使用循环来运行所有内容, await将把控制权交还给循环,以便它可以安排下一个协程运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM