我正在编写一个通过网络连接定期检索数据的 GUI 应用程序。由于此检索需要一段时间,这会导致 UI 在检索过程中无响应(无法拆分为更小的部分)。这就是我想将 Web 连接外包给单独的工作线程的原因。
[是的,我知道,现在我有 two problems 。]
无论如何,应用程序使用 PyQt4,所以我想知道更好的选择是:使用 Qt 的线程还是使用 Python threading
模块?每个的优点/缺点是什么?还是您有完全不同的建议?
编辑(重新赏金):虽然在我的特殊情况下的解决方案可能会使用像 Jeff Ober 和 Lukáš Lalinský 建议的非阻塞网络请求(所以基本上将并发问题留给网络实现) ,我仍然希望对一般问题有更深入的回答:
在原生 Python 线程(来自 threading
模块)上使用 PyQt4(即 Qt)线程有哪些优点和缺点?
编辑 2:感谢大家的回答。虽然没有 100% 的一致意见,但似乎普遍认为答案是“使用 Qt”,因为这样做的好处是与库的其余部分集成,而不会造成真正的缺点。
对于希望在两种线程实现之间进行选择的任何人,我强烈建议他们阅读此处提供的所有答案,包括 abbot 链接到的 PyQt 邮件列表线程。
我为赏金考虑了几个答案;最后我选择了方丈作为非常相关的外部引用;然而,这是一个千钧一发的机会。
再次感谢。
最佳答案
这是 discussed不久前在 PyQt 邮件列表中。引用 Giovanni Bajo 的 comments关于主题:
It's mostly the same. The main difference is that QThreads are better integrated with Qt (asynchrnous signals/slots, event loop, etc.). Also, you can't use Qt from a Python thread (you can't for instance post event to the main thread through QApplication.postEvent): you need a QThread for that to work.
A general rule of thumb might be to use QThreads if you're going to interact somehow with Qt, and use Python threads otherwise.
PyQt 的作者对此主题的一些较早评论:“它们都是相同 native 线程实现的包装器”。两种实现都以相同的方式使用 GIL。
关于python - PyQt 应用程序中的线程 : Use Qt threads or Python threads?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1595649/