如何启动协程并继续执行同步任务?
How to start coroutines and continue with synchronous tasks?
我正在尝试理解 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()
)吗?
await
在某个点停止执行,你做 await a()
,你在 a()
中有一个无限循环,所以逻辑上 b()
不会被调用.把它想象成在 mainloop()
.
中插入 a()
考虑这个例子:
async def main():
while True:
await asyncio.sleep(1)
print('in')
print('out (never gets printed)')
为了实现你想要的,你需要创建一个可以管理多个协程的未来。 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()
我正在尝试理解 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()
)吗?
await
在某个点停止执行,你做 await a()
,你在 a()
中有一个无限循环,所以逻辑上 b()
不会被调用.把它想象成在 mainloop()
.
a()
考虑这个例子:
async def main():
while True:
await asyncio.sleep(1)
print('in')
print('out (never gets printed)')
为了实现你想要的,你需要创建一个可以管理多个协程的未来。 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()