具有巨大时间延迟差异 运行 的线程顺序

Threads with huge time delay difference running sequentially

我目前正在寻找一种方法来向我用 pyQt 编写的应用程序添加 TCP/IP 通信。虽然我测试过的 none 代码似乎可以工作(在大多数情况下它只是冻结了 GUI),但我开始研究线程。

在堆栈上找到了一些代码并向其添加了睡眠延迟。我已经按顺序阅读了一些有关线程的信息 运行,我想我有点了解线程的工作原理,但我得到的结果确实不是我所期望的。

import sys
from PyQt5 import QtWidgets, QtCore, QtGui
import time
import threading

class Example(QtWidgets.QWidget):

    def __init__(self):
        super(Example, self).__init__()
        QtWidgets.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
        btn = QtWidgets.QPushButton('Button', self)
        self.show()
        self.background = MyThread(self)
        t = threading.Thread(target=self.background.process)
        t2 = threading.Thread(target=self.background.process2)
        t.start()
        t2.start()
        self.background.notify.connect(self.notify)
        self.background.notify2.connect(self.notify2)

    @QtCore.pyqtSlot()
    def notify(self):
        print("I have been notified")

    @QtCore.pyqtSlot()
    def notify2(self):
        print("I have been notified two")

class MyThread(QtCore.QObject):

    notify = QtCore.pyqtSignal()
    notify2 = QtCore.pyqtSignal()

    def __init__(self, parent):
        super(MyThread, self).__init__(parent)
        self.should_continue = True

    def process(self):
        while self.should_continue:
            # Here, do your server stuff.
            time.sleep(0.001)
            self.notify.emit()

    def process2(self):
        while self.should_continue:
            # Here, do your server stuff.
            time.sleep(0.1)
            self.notify2.emit()

def main():

    app = QtWidgets.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

为什么我得到:

I have been notified
I have been notified two
I have been notified two
I have been notified
I have been notified
I have been notified two
I have been notified
I have been notified two

而不是

I have been notified
I have been notified two
I have been notified
I have been notified
I have been notified
I have been notified
I have been notified

notify 与 notify2 打印数的比率不应该等于时间延迟比率吗?

您将错误的方法连接到错误的信号。 process2 发出 notify2,而不是 notify,因此您必须更改:

self.background.notify.connect(self.notify)
self.background.notify.connect(self.notify2)

self.background.notify.connect(self.notify)
self.background.notify2.connect(self.notify2)

它会正常工作。