我正在使用
Python 3.7
(有
PyQt5
对于GUI)在
计算机我的应用程序需要一些多线程处理。要做到这一点,我使用
QThread()
.
我需要用互斥来保护一些代码。我想我有以下两个选择:用Python的锁来保护它
threading
模块或带有
QMutex()
.
1.使用threading.Lock()进行保护
import threading
...
self.mutex = threading.Lock()
我如何使用它:
def protected_function(self):
if not self.mutex.acquire(blocking=False):
print("Could not acquire mutex")
return
# Do very important
# stuff here...
self.mutex.release()
return
https://docs.python.org/3/library/threading.html#threading.Lock
2.使用QMutex()进行保护
要创建互斥对象,请执行以下操作:
from PyQt5.QtCore import *
...
self.mutex = QMutex()
以及如何使用它:
def protected_function(self):
if not self.mutex.tryLock():
print("Could not acquire mutex")
return
# Do very important
# stuff here...
self.mutex.unlock()
return
QMutex()
在这里:
http://doc.qt.io/qt-5/qmutex.html
3.兼容性
我想知道:
-
是
threading.Lock()
与由金属制成的螺纹兼容
QThread()
-
是
是否与普通Python线程兼容?
换句话说,如果这些东西混在一起有什么大不了的吗例如:一些python线程在应用程序中运行,在一些QThread的旁边,一些东西受
threading.Lock()
,其他资料由
QMutex()