【发布时间】:2019-03-15 22:24:27
【问题描述】:
如果我在没有任何添加任务的情况下启动循环,有人可以解释一下为什么我不能执行我的任务吗? (Python 3.7)
import asyncio
import threading
def run_forever(loop):
loop.run_forever()
async def f(x):
print("%s executed" % x)
# init is called first
def init():
print("init started")
loop = asyncio.new_event_loop()
# loop.create_task(f("a1")) # <--- first commented task
thread = threading.Thread(target=run_forever, args=(loop,))
thread.start()
loop.create_task(f("a2")) # <--- this is not being executed
print("init finished")
如果我对# loop.create_task(f("a1")) 发表评论,执行是:
init started
init finished
未注释的执行是:
init started
init finished
a1 executed
a2 executed
为什么会这样?我想创建一个循环并在将来添加任务。
【问题讨论】:
标签: python-3.x multithreading python-asyncio python-3.7