简体   繁体   English

如何在 python3 中确定主线程 pyqt5 的优先级?

[英]How to prioritize main pyqt5 thread in python3?

I have made a gui application with PyQt5 in python 3.8.我在 python 3.8 中用 PyQt5 制作了一个 gui 应用程序。 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).但是当我从我的 GUI 命令执行繁重的多线程 CPU 密集型任务时(gui 线程未参与),GUI 变得非常无响应(很可能是由于 CPU 集中在工作任务上)。

My question is, is there any way to prioritize gui's thread in python so that workers don't slow the GUI down?我的问题是,有没有什么办法可以优先考虑 python 中的 gui 线程,这样工作人员就不会减慢 GUI 的速度? I use threading.Thread(target=task, daemon=True).start() to run threads.我使用threading.Thread(target=task, daemon=True).start()来运行线程。

thread priority is not something you can do, but there are a few ways around it to have a responsive GUI.线程优先级不是你能做的,但有几种方法可以绕过它来获得响应式 GUI。

  1. change sys.setswitchinterval to a lower value (perhaps to 0.001)sys.setswitchinterval更改为较低的值(可能为 0.001)

which makes python switch threads more frequently so the GUI can respond more quickly to events, and will feel more responsive.这使得 python 更频繁地切换线程,因此 GUI 可以更快地响应事件,并且感觉响应更快。

  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.除了可以使用更多的 CPU 内核这一事实之外,您还可以控制每个进程的关联性和优先级,因此您可以保证您的 GUI 即使在负载系统上也保持更高的优先级。

  1. release the GIL more often更频繁地发布 GIL

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.通常,如果您可以在 python 中完成的操作和 C 扩展(如 numpy 或 pandas)中完成的操作之间进行选择,则 C 扩展可以释放 GIL,因此您的 GUI 可以保留 GIL 更长时间。

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.在上述解决方案中,最常用的(即使在非 python 程序中)是使用多处理,因为它比“响应式 GUI”有更多好处,第三个更像是“编码时的推荐”,所以保留它在编写应用程序时请记住。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM