Thread Safety with PySide
PySide is a nice Python wrapper for Qt which hides some internal aspects of it. For instance, thread safety: what's safe when it comes to signals and slots?
1 Signals and Slots in Plain C++ Qt
Are they safe? The Qt documentation on Signals and Slots Across Threads suggests the right connection will be automatically picked – that'll be a queued connection in the case of multithreading to keep it all safe. They offer the Mandelbrot Example in C++, which we have for Python too:
- The signal is emitted from the auxiliary thread.
- The slot is run from the main Qt thread.
- The connection is made from the main Qt thread.
2 Signals and Slots in PySide
The PySide Mandelbrot Example uses the traditional signals and slots syntax. Using the new syntax would have:
the signal be defined in the QThread class definition:
Note how you can specify the arguments that the slot would have to take. It would be emitted from an instance of this class;class CliThread(QThread): actionRequested = Signal(str, str)
the slot still be defined from the main Qt thread, not necessarily in a class. The documentation suggests annotations but I haven't found any need for them to make it all work:
The slot is a class attribute here, but again, there's no need for that, of course.def act(self, action, arg): getattr(self, action)(arg)
the connection still be made from the main Qt thread:
clithread.actionRequested.connect(pool.act)