0

I am currently using threading.Thread() to execute python-functions which are time-consuming, and therefore should not impact my user interface. Typically, the functions to be executed are class functions, and are moved into threads in other class functions of the same class with a code similar to

self.t = threading.Thread(target = self.long_function_to_run, args=(), kwargs={})
self.t.daemon = True
self.t.start()

Now, I would like to move everything to use QThread instead, to be able to use signals and slots instead of having to rely on Queue()-queues.

Nevertheless, to do that, I have to create my own worker-class, subclass it from either QObject or QThread (as described in https://stackoverflow.com/a/6789205/2546099), and then execute this class. This would add significant overhead, and therefore I was wondering if there are any alternatives similar to my initial approach, without subclassing?

arc_lupus
  • 3,942
  • 5
  • 45
  • 81
  • If you need custom signals, you need subclasses. – musicamante Jul 04 '22 at 13:23
  • What if I don't need custom signals? And which signals are custom, and which are not? – arc_lupus Jul 04 '22 at 13:26
  • A custom signal is one you create, otherwise you use those the class already has. You'd probably need to communicate the results of those threads with the main, which means that, at some point, you'll emit a signal with your own data; since you're not using an instance for the thread, there's no reference for the data assigned to it, so you can't even use the existing QThread signals, as they'd be pointless for that purpose. Instead of worrying about overhead, try to understand if you can optimize the way you "spawn" threads, and see if you can create a common "API" to modularize your tasks. – musicamante Jul 04 '22 at 13:34
  • @musicamante: If I understand correctly: A common API would be a single class responsible for taking over the corresponding function, and execute it in a separate thread, for example? Or are there other examples? – arc_lupus Jul 04 '22 at 13:37
  • I used quotes around "API" to indicate that it's more of a "concept". But, fundamentally, yes: you could use a template QThread subclass, with a generic signal (that could emit any data type), and then create new instances that target a defined function and interface with their "parent" thread to emit the result of their processing. – musicamante Jul 04 '22 at 14:57

0 Answers0