Handling and Sharing Data Between Threads

by Aquiles Carattino Aug. 6, 2019 threading threads data sharing

This is a companion discussion topic for the original entry at http://www.pythonforthelab.com/blog/handling-and-sharing-data-between-threads/

Hello - Your posts are very informative, but one thing that ‘bothers’ me is that you derive your threads from the Thread class. Other sources on the net discourage this strongly and suggest that the thread should be created and then ‘moveToThread’ should be called so that control is passed to the moved thread. Like this:

self.Thread1 = QThread()
            self.Thread2 = QThread()
            self.Worker1 = wkr.Worker(self.IP,20080, self.nBytes)
            self.Worker2 = wkr.Worker(self.IP,20081, self.nBytes)
            self.Thread1.started.connect(self.Worker1.work) #Slot 1
            self.Thread2.started.connect(self.Worker2.work) #Slot 2
            self.Thread1.start() #start work(1)
            self.Thread2.start() #start work(2)

Do you use this technique anywhere?

Hello Dave, welcome to Python for the Lab.

There are several things to note. One is that in this tutorial I am using Python threads, not QThreads. And I am not subclassing them, but just using the standard syntax of Thread(target=func).

Then, regarding moteToThread or subclassing QThread, they are just used differently. For example, you can subclass QThread when you want to have finer control on the loop itself. While moveToThread allows you to quickly push to a separate thread any function that may block your UI.

So, there is no should, but a matter of convenience in using one or the other. If in doubt, check the official docs which show you how to use moveToThread and subclassing QThread. Each pattern is handy in its own way.