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

Is threading.Lock() compatible with QThread() and is QMutex() compatible with python threads?

我在 [ 上使用 Python 3.7(GUI 使用 PyQt5) =84=]10台电脑。我的应用程序需要一些多线程。为此,我使用 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

您可以在此处找到 Python 文档: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() 上找到 Qt5 文档:http://doc.qt.io/qt-5/qmutex.html


3。兼容性

我想知道:

  1. threading.Lock()QThread() 制作的线程兼容吗?

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

换句话说,如果这些东西混在一起有什么大不了的吗? - 例如:应用程序中的几个 python 线程 运行,紧挨着一些 QThread,一些东西受 threading.Lock() 保护,其他东西受 QMutex().

TL;DR;结合使用无所谓


QThreads 不是 Qt 线程,也就是说它们不是新线程,而是 管理的 class每个 OS 的本机线程和 Python 线程 也会发生同样的情况,它们也是处理本机线程的包装器。同样的事情发生在 QMutexthreading.Lock() 上,所以使用一个或另一个是无关紧要的,因为在后台你使用的是本机线程和互斥体。