【发布时间】:2017-08-20 19:09:40
【问题描述】:
我试图了解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')
我现在尝试根据documentation 将此移植到asyncio。
问题 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()
问题2:输出是a的序列,说明b()协程根本没有被调用。 await 不是应该启动 a() 并返回执行(然后启动 b())吗?
【问题讨论】:
标签: python multithreading asynchronous async-await python-asyncio