Pyqt Qsemaphore Example

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?

0 -1
Tube Traffic Ninja

Tube Traffic Ninja

Discover How You Can Quickly And Easily Dominate Google and YouTube... With Simple Cash Generating Videos. Did you know that YouTube is the second largest search website on the entire Internet? YouTube gets more daily searches than Bing and Yahoo. In fact, there is only one search engine that gets more action.

Get My Free Ebook


Post a comment