1. import asyncio
    2. from threading import Thread
    3. async def create_task(event_loop):
    4. i = 0
    5. while True:
    6. # 每秒产生一个任务, 提交到线程里的循环中, event_loop作为参数
    7. asyncio.run_coroutine_threadsafe(production(i), event_loop)
    8. await asyncio.sleep(1)
    9. i += 1
    10. async def production(i):
    11. while True:
    12. print("第{}个coroutine任务".format(i))
    13. await asyncio.sleep(1)
    14. def start_loop(loop):
    15. # 运行事件循环, loop作为参数
    16. asyncio.set_event_loop(loop)
    17. loop.run_forever()
    18. thread_loop = asyncio.new_event_loop() # 创建事件循环
    19. run_loop_thread = Thread(target=start_loop, args=(thread_loop,)) # 新起线程运行事件循环, 防止阻塞主线程
    20. run_loop_thread.start() # 运行线程,即运行协程事件循环
    21. main_loop = asyncio.new_event_loop()
    22. main_loop.run_until_complete(create_task(thread_loop)) # 主线程负责create coroutine object