Python3 Asyncio创建任务时遇到问题

时间:2019-01-25 04:19:30

标签: python python-3.x multithreading python-asyncio

已经完成了大多数示例,但仍在使用Python学习异步。我遇到了麻烦,为什么这个示例代码不会显示“我是异步的”。

import asyncio
from threading import Thread

async def cor1():
   print("i am async!")

def myasync(loop):
   print("Async running")
   loop.run_forever()
   print("Async ended?")

def main():
   this_threads_event_loop = asyncio.get_event_loop()
   t_1 = Thread(target=myasync, args=(this_threads_event_loop,));
   t_1.start()
   print("begining the async loop")
   t1 = this_threads_event_loop.create_task(cor1())
   print("Finsihed cor1")

main()

1 个答案:

答案 0 :(得分:2)

您的代码尝试将任务从另一个线程提交到事件循环。为此,您必须使用run_coroutine_threadsafe

def main():
   loop = asyncio.get_event_loop()
   # start the event loop in a separate thread
   t_1 = Thread(target=myasync, args=(loop,));
   t_1.start()
   # submit the coroutine to the event loop running in the
   # other thread
   f1 = asyncio.run_coroutine_threadsafe(cor1(), loop)
   # wait for the coroutine to finish, by asking for its result
   f1.result()
   print("Finsihed cor1")

请注意,仅在特殊情况下(例如,将asyncio引入需要逐步添加新功能的旧版应用程序时),才应将asyncio和线程组合在一起。如果您正在编写新代码,则几乎可以肯定希望main是一个协程,使用asyncio.run(main())从顶层运行。

要从asyncio代码运行旧版同步功能,您始终可以使用run_in_executor