Writing threaded servers using PyQt's threading and networking classes is relatively straightforward. For non-GUI servers, it is possible to use QCore-Application rather than QApplication, or to avoid using PyQt classes at all, relying instead on the Python standard library threading and networking classes, or using Twisted.
Farming out processing to secondary threads is not difficult in theory, but in practice we must be very careful to ensure that any data that is accessible by more than one thread uses a protection mechanism such as QMutex, QReadWrite-Lock,or QSemaphore. Inside the context of a protection mechanism we must make sure that we do the least amount of work possible to minimize the time that other threads might be blocked. And in the case of reading data, especially if the data is not too large, it is often best to copy it to avoid the risk of accessing it outside the scope of the protection.
It is quite common for the primary thread to communicate with secondary threads by calling the secondary threads' methods—for example, start() to start them and stop() to stop them. Secondary threads can communicate with the primary thread by emitting signals that the primary thread connects to. Both primary and secondary threads can also use shared data structures protected by QMutexes, QReadWriteLocks, or QSemaphores—with one common scenario being that the primary reads and the secondary threads read and write shared data. Threads may need to protect accesses to their own data—for example to a secondary thread's stopped variable—since more than one of their methods may be active at the same time (e.g., both run() and stop() in a secondary thread).
Multithreaded programs are more difficult to write and maintain than single-threaded programs, so it is often worthwhile to see whether simpler alternatives, such as calling QApplication.processEvents() or calling external processes using QProcess, can be used instead.
Was this article helpful?
Download Tube Jacker And Discover Everything You Need To Know About Jacking Unlimited Traffic From The Video Giant. The drop dead easy way to create winning video campaigns that will FLOOD your website with unstoppable FREE traffic, all on complete and total autopilot. How to exploit a sneaky method of boosting exposure and getting your videos to the top of Google within 72 hours, guaranteed.