<p>我想知道python3.6和asyncio的并发性是如何工作的。我的理解是,当解释器执行<code>await</code>语句时,它会将其留在那里,直到等待过程完成,然后继续执行另一个协同程序任务。但我在下面的代码中看到的并不是这样。程序同步运行,逐个执行任务。在</p>
<p>我的理解和实现代码有什么问题?在</p>
<pre><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.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>(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()
</code>
</pre>