代码之家  ›  专栏  ›  技术社区  ›  K.Mulier

threading.Lock()是否与QThread()兼容,QMutex()是否与python线程兼容?

  •  0
  • K.Mulier  · 技术社区  · 7 年前

    我正在使用 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.兼容性

    我想知道:

    1. threading.Lock() 与由金属制成的螺纹兼容 QThread()

    2. 是否与普通Python线程兼容?

    换句话说,如果这些东西混在一起有什么大不了的吗例如:一些python线程在应用程序中运行,在一些QThread的旁边,一些东西受 threading.Lock() ,其他资料由 QMutex()

    1 回复  |  直到 7 年前
        1
  •  1
  •   eyllanesc    7 年前

    TL;博士 把它们结合起来使用是无关紧要的。


    Qt线程 ,也就是说,它们不是新线程,而是 管理 每个操作系统的本机线程以及 Python线程 这也是处理本机线程的包装器。同样的事情也发生在 QMutex threading.Lock() 因此,使用其中一个是无关紧要的,因为在后台您使用的是本机线程和互斥。