并行运行的自定义环与主事件循环
问题描述:
如何运行一个无限循环并行运行的自定义环与主事件循环
# custom infinite loop
while 1:
print("Hello\n")
平行的tornado
主事件循环?
if __name__ == "__main__":
# Main event loop
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
答
你可以在另一个线程中运行它(并处理关联的同步)。或者你可以使它成为一个协程,并定期向IOLoop屈服(大概是你的代码的实际版本正在休眠,而不是仅仅是忙碌循环;在这种情况下,你会使用await tornado.gen.sleep()
答
我不知道它是否是最佳答案,但在线程上运行每个循环对我而言运行良好。
import threading
application.listen(8888)
event_loop_thread = threading.Thread(target=tornado.ioloop.IOLoop.instance().start)
event_loop_thread.daemon = True
event_loop_thread.start()
custom_loop_thread = threading.Thread(target=custom_loop)
custom_loop_thread.daemon = True
custom_loop_thread.start()
while 1:
pass