我想知道如何在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
会将控制权返回给循环,以便它可以安排下一个协程运行。