WoJ*_*WoJ 5 python multithreading asynchronous async-await python-asyncio
我正在努力理解asyncio和挖掘我的未成年人threading.我将以两个无限运行的线程和一个非线程循环(所有这些都输出到控制台)为例.
该threading版本是
import threading
import time
def a():
while True:
time.sleep(1)
print('a')
def b():
while True:
time.sleep(2)
print('b')
threading.Thread(target=a).start()
threading.Thread(target=b).start()
while True:
time.sleep(3)
print('c')
Run Code Online (Sandbox Code Playgroud)
问题1:我不明白如何添加非线程任务,因为我看到的所有示例都在程序结束时显示了一个持续循环来控制asyncio线程.
然后我希望至少有两个并行运行的第一个线程(a和b)(最坏的情况是,将第三c个线程添加为线程,放弃混合线程和非线程操作的想法):
import asyncio
import time
async def a():
while True:
await asyncio.sleep(1)
print('a')
async def b():
while True:
await asyncio.sleep(2)
print('b')
async def mainloop():
await a()
await b()
loop = asyncio.get_event_loop()
loop.run_until_complete(mainloop())
loop.close()
Run Code Online (Sandbox Code Playgroud)
问题2:输出是一个序列a,表示b()根本没有调用协程.是不await应该开始a()并回到执行(然后开始b())?
await在某个点停止执行,你这样做await a(),并且在 中有一个无限循环a(),所以逻辑上b()不会被调用。想象一下,如果您a()插入mainloop().
考虑这个例子:
async def main():
while True:
await asyncio.sleep(1)
print('in')
print('out (never gets printed)')
Run Code Online (Sandbox Code Playgroud)
为了实现你想要的,你需要创建一个管理多个协程的未来。asyncio.gather是为了那个。
import asyncio
async def a():
while True:
await asyncio.sleep(1)
print('a')
async def b():
while True:
await asyncio.sleep(2)
print('b')
async def main():
await asyncio.gather(a(), b())
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
828 次 |
| 最近记录: |