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

问题描述 投票:-1回答:1

我正在寻找一种方法来添加TCP / IP通信到我用pyQt编写的应用程序。虽然我测试的代码似乎都没有工作(在大多数情况下它只是冻结了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打印数量的比例等于时间延迟比率?

python pyqt5 python-multithreading
1个回答
0
投票

您已将错误的方法连接到错误的信号。 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)

它会按预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.