控制 Twisted 反应器使其无阻塞的最佳方法是什么?
我不想运行reactor.run(),而是偶尔调用其他东西(我不知道,比如reactor.runOnce()或其他东西),同时维护自己的主循环。扭曲是否有最佳实践?
Instead of running reactor.run(), I'd like to call something else (I dunno, like reactor.runOnce() or something) occasionally while maintaining my own main loop. Is there a best-practice for this with twisted?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的。最佳实践是,这是一个坏主意,而且您永远不需要这样做。它不适用于所有反应器,并且您当然不能有两个不同的库想要执行此操作。
为什么需要维护自己的主循环?有可能,它类似于“我想使用 PyGame”或“我正在编写一个 GUI 程序,我想使用 GTK 的主循环”或“我在 Blender 中使用 Twisted,它有自己的事件处理”。如果是这种情况,您应该提出特定的问题,因为每个问题都有自己的答案。
如果您绝对需要执行此操作(并且再次强调:您不需要),则执行此操作的方法是定期调用
reactor.iterate()
。这会很慢,会破坏信号处理,并且对于reactor.stop()
具有不稳定的语义。它会在你的程序中引入很多本来不会存在的错误,当你需要帮助诊断这些错误时,如果你问 Twisted 开发团队的某个人,他们会告诉你的第一件事是“停止这样做,你不这样做”不需要这样做”。Yes. The best practice is that this is a bad idea, and that you never really need to do it. It doesn't work with all reactors, and you certainly can't have two different libraries which want to do this.
Why do you need to maintain your own main loop? Chances are, it's something like "I want to work with PyGame" or "I am writing a GUI program and I want to use GTK's mainloop" or "I'm using Twisted from within Blender and it has its own event-handling". If this is the case, you should ask that specific question, because each one of those has its own answer.
If you absolutely need to do this (and, again: you don't) the way to do it is to call
reactor.iterate()
periodically. This will be slow, break signal handling, and have wonky semantics with respect toreactor.stop()
. It will introduce lots of bugs into your program that wouldn't otherwise be there, and when you need help diagnosing them, if you ask someone on the Twisted dev team, the first thing they will tell you is "stop doing that, you don't need to do it".