0

Having lots of troubles with a multithreaded program in which i am building a gui to automate the processing of neural data by using an API in the backend. I have tried looking at many different resources but I am specifically having trouble with keeping the thread alive when I need to call the same "run_worker" function from the WorkerThread multiple times, since the "run_worker" function will emit a finished signal once it is done. How can I fix this so that the thread can continue after each step of data processing when a button is clicked? Here is my current code for the WorkerThread and UI and an example of a function I need to call when the evee button is clicked in the UI class.

from PyQt5.QtCore import QObject, pyqtSignal as Signal, pyqtSlot as Slot

class WorkerThread(QObject):
    finished = Signal()
    #progress = Signal()

    def __init__(self, parent=None):
        super(WorkerThread, self).__init__(parent)
        

    @Slot()
    def run_worker(self, process_object, function, *args):
        func = getattr(process_object, function)
        if func is not None and callable(func):
            if args:
                func(*args)
                #self.finished.emit()
            else:
                func()
        else:
            raise ValueError("Provided function is not callable.")
        self.finished.emit()
class UI(QMainWindow):
    work_requested = Signal()

    def  __init__(self):
        super(UI, self).__init__()
        loadUi("processing_gui.ui", self)
        self.setFixedWidth(1200)
        self.setFixedHeight(1080)
        #SETUP WORKER THREAD
        self.worker_thread = QThread() #also tried initializing as QThread(parent=self)
        self.worker = WorkerThread()
        #self.worker.finished.connect(self.worker.deleteLater) #?
        self.work_requested.connect(self.worker.run_worker)
        self.worker_thread.start()
        # show the window
        self.show()

        self.timeseries_start = False
        self.lr_complete = False
        self.preprocess_complete = False 
        self.evee.clicked.connect(self.on_preprocess_click) #preprocess, bandpass filter, mean projection calculation, and motion correction

    def start(self, process_object, function, *args):
        self.work_requested.emit(process_object, function, *args)

    def on_preprocess_click(self):
        if self.timeseries_start:
            try:
                self.show_complete_dialog('Preprocessing has begun!')
                self.evee.setEnabled(False)
                self.start(self.timeseries_process_object, "preprocess", 2, 4)
            except:
                self.show_error_message(
                    'Preprocessing could not be completed because -PP files already exist. Recheck file names or delete the files ending in -PP from processed directory to try again.')
                return
            try: 
                self.start(self.timeseries_process_object, "bandpass_filter")
            except:
                self.show_error_message(
                    'Bandpass filtering could not be completed because the -PP-BP files already exist. Delete them from the processed directory to continue.'
                )
                return
            try:
                self.start(self.timeseries_process_object, "mean_projection_frame")
            except: 
                self.show_error_message('Mean projection frame could not be calculated because it was already calculated. Delete -mean_image.isxd files form processed folder to continue')
                return
            try:
                self.start(self.timeseries_process_object, "motion_correction")
            except:
                self.show_error_message(
                    'Motion correction could not be completed because the -PP-BP-MC files already exist. Delete them from the processed directory to continue'
                )
                return
            self.show_complete_dialog('Proprocessing has been completed!')
            self.preprocess_complete = True
            self.evee.setEnabled(True)

I have tried using a QQueue in the worker thread but continued to get import errors despite trying to upgrade and reinstall in my virtual environment. I would appreciate any insight as to how I can keep my thread running as I call the same "run_worker" function dynamically multiple times within my on click functions. The functions I am running in the backend take a significant amount of time (about 40 mins for some buttons) so my GUI continues to be unresponsive and gives me the Qthread destroyed error while its running.

4
  • According to your code, you are not using threading: you just create a QThread and start it, but nothing else is done there. Please provide a valid and comprehensive minimal reproducible example. Sep 21 at 18:28
  • You forgot to use QObject.moveToThread. Besides, I wouldn't advise on creating a worker capable of calling any function on another thread. While the idea seems promising, it can create a lot of problems for you in the future, as the project scales up. You should only call these functions in another thread, if you can guarantee they're not accessing shared data/resources at the same time (without being protected by QMutexes) inside their scopes.
    – Carl HR
    Sep 21 at 18:32
  • Storing and using a single instance of QThread + WorkerThread is ideal if you want to run one function after another in a sequence. For example: if you want to call A, B and C functions, B will only be executed after A finishes, and C will only execute after B finishes. That's what your example does. If you want to run A, B and C simultaneously, you should create/manage multiple instances of QThreads + WorkerThreads (though it is easier said than done).
    – Carl HR
    Sep 21 at 18:32
  • @CarlHR What you are pointing out is correct. Still, the error in the title shows that, in some way, the OP is using a "QThread-ed function": they are probably trying to create a further QThread within those timeseries_process_object functions they're getting with getattr, but they didn't keep a persistent reference to it, which is what normally causes that error. Sep 22 at 3:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.