Home > Back-end >  How to prioritize main pyqt5 thread in python3?
How to prioritize main pyqt5 thread in python3?

Time:01-14

I have made a gui application with PyQt5 in python 3.8. But when I order from my GUI to perform heavy multithreaded CPU-intensive task (the gui thread isn't engaged), the GUI becomes very non-responsive (most likely due to CPU being concentrated on worker tasks).

My question is, is there any way to prioritize gui's thread in python so that workers don't slow the GUI down? I use threading.Thread(target=task, daemon=True).start() to run threads.

CodePudding user response:

thread priority is not something you can do, but there are a few ways around it to have a responsive GUI.

  1. change sys.setswitchinterval to a lower value (perhaps to 0.001)

which makes python switch threads more frequently so the GUI can respond more quickly to events, and will feel more responsive.

  1. use multiprocessing instead of threading for computations.

aside from the fact that you get to use more CPU cores, you also get to control the affinity and priority of each process, so you can guarantee your GUI stays a higher priority even on a loaded system.

  1. release the GIL more often

usually if you have a choice between an operation being done in python and another being done in a C extension (like numpy or pandas), the C extension can release the GIL, so your GUI can hold the GIL for a longer time.

out of the above solutions, the one most used (even in non-python programs) is using multiprocessing, as it has more benefits than just "responsive GUI", the third one is more of a "recommendation while coding", so keep it in mind when coding the application.

  • Related