2
votes

I am building a GUI with a socket connection running in a backround thread in PyQt5. Everything is working pretty well except the Qthread never emits the finished signal. Maybe this isn't a problem and I could change my implementation around to work around it, but is the expected behavior that the Qthread would continue to run once the object that has been moved has stopped doing anything?

Should I write a function in the main class to stop the thread once I'm done with it, or can I just move new things to that thread with no consequences?

class MyClass(PyQt5.QtWidgets.QMainWindow)
    def __init__(self, parent=None):

        # Setup thread for the socket control
        self.simulThread = PyQt5.QtCore.QThread()
        self.socketController = SocketController()
        self.socketController.moveToThread(self.simulThread)
        self.simulThread.started.connect(self.socketController.controlSocket)

        self.simulThread.finished.connect(self.deadThread)

        # Bind controls to events
        self.ui.buttonConnect.clicked.connect(self.simulThread.start)
        self.ui.buttonDisconnect.clicked.connect(lambda: self.socketController.stop())

   def deadThread(self, data):
       print ("THREAD IS DEAD.")

class SocketController(PyQt5.QtCore.QObject):
    finished       = PyQt5.QtCore.pyqtSignal()

    def __init__(self):
        super(SocketController, self).__init__()
        self.run = True;

    def controlSocket(self):
        #setup the socket

        while self.run:
            # do socket stuff
            time.sleep(1)

        #close the socket
        self.finished.emit()

    def stop(self):
        self.run = False;
3
Do you mean that THREAD IS DEAD gets printed? - Oliver
@Schollii it does not get printed. - Ian

3 Answers

0
votes

A QThread has it's own event loop to handle signals. The controlSocket method blocks this event loop until self.run == False. But this never happens because self.run is only set to False when control is returned to the event lop and it can process the signal that runs the stop method.

You probably want to rearchitect your thread so that instead of having a while loop which blocks the QThread event loop, you construct a QTimer in the thread which calls the #do socket stuff code every 1 second. This way, control is returned to the threads event loop and it can process the stop signal (which would be changed to stop the QTimer from triggering again)

0
votes

The answer is actually a combination of what three_pineapples and OP posted in their answers:

  1. As noted by three_pineapples, the main problem is that controlSocket(), which gets called by the thread event loop when started signal is emitted, doesn't return until the stop() method gets called. However, in the OP's design, the stop() method can only be called by Qt if the socket thread can process events (since this is how cross-thread signals are dispatched, via the event loops). This is not possible while controlSocket() is busy looping and sleeping.
  2. In order for the thread to exit, its event loop must be stopped.

The first issue must be fixed by either allowing the thread to process events during the loop, or by using a timer instead of a loop. Processing events is shown in this piece of code, based on the OP code:

import time

from PyQt5.QtWidgets import QMainWindow, QWidget, QPushButton, QApplication, QHBoxLayout
from PyQt5.QtCore import QThread, QObject, pyqtSignal

class MyClass(QWidget):
    def __init__(self, parent=None):
        super().__init__()

        self.resize(250, 150)
        self.setWindowTitle('Simple')

        # Setup thread for the socket control
        self.socketController = SocketController()

        self.simulThread = QThread()
        self.socketController.moveToThread(self.simulThread)
        self.simulThread.started.connect(self.socketController.controlSocket)
        self.simulThread.finished.connect(self.deadThread)

        # Bind controls to events
        self.buttonConnect = QPushButton('connect')
        self.buttonConnect.clicked.connect(self.simulThread.start)

        self.buttonDisconnect = QPushButton('disconnect')
        self.buttonDisconnect.clicked.connect(self.socketController.stop)

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(self.buttonConnect)
        hbox.addWidget(self.buttonDisconnect)
        self.setLayout(hbox)

    def deadThread(self, data):
        print("THREAD IS DEAD.")


class SocketController(QObject):
    finished = pyqtSignal()

    def __init__(self):
        print('initialized')
        super().__init__()
        self.run = True

    def controlSocket(self):
        # setup the socket

        print('control socket starting')
        while self.run:
            # do socket stuff
            app.processEvents()
            print('control socket iterating')
            time.sleep(1)

        # close the socket
        self.finished.emit()
        print('control socket done')

    def stop(self):
        print('stop pending')
        self.run = False


app = QApplication([])
mw = MyClass()
mw.move(300, 300)
mw.show()
app.exec()

The QTimer is a little more complicated, but the idea is to have controlSocket() only do one iteration of the loop, and call it repeatedly via QTimer:

QTimer.singleShot(0, self.controlSocket)

and

def controlSocket(self):
    # do socket stuff, then:
    if self.run:
        QTimer.singleShot(1000, self.controlSocket)
    else:
        self.finished.emit()

Either of the above approaches fixes the first problem, and allows the SocketController to stop doing its socket-related work.

The second problem is that even after the socket controller is done its job, the thread loop is still running (the two loops are independent). To make the event loop exit, it must be stopped via the thread's quit() method. The quit and the stop should be done together:

class MyClass(QWidget):
    def __init__(self, parent=None):
        ...

        self.buttonDisconnect = QPushButton('disconnect')
        self.buttonDisconnect.clicked.connect(self.stop)

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(self.buttonConnect)
        hbox.addWidget(self.buttonDisconnect)
        self.setLayout(hbox)

    def stop(self):
        self.simulThread.quit()
        self.socketController.stop()
-1
votes

Ok, so I found A solution, but I don't really know if its correct. Instead of mapping the disconnect button to the socket stop function, I mapped it to function defined in MyClass that calls a new function I wrote called controlDisconnect which also tells the thread explicitly to quit.

# The changed line
self.ui.buttonDisconnect.clicked.connect(self.controlDisconnect)

def controlDisconnect(self):
    self.socketController.stop()
    self.simulThread.quit()

While this is working (the thread prints out the message that indicates it died), I'm not sure its really good practice. There should probably at least be some code to make sure the socketController has actually stopped before telling the thread to quit.