内容表

上一话题

QMutex

下一话题

QObject

QMutexLocker

QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes. 更多

Inheritance diagram of PySide2.QtCore.QMutexLocker

概要

函数

详细描述

锁定和解锁 QMutex in complex functions and statements or in exception handling code is error-prone and difficult to debug. QMutexLocker can be used in such situations to ensure that the state of the mutex is always well-defined.

QMutexLocker should be created within a function where a QMutex needs to be locked. The mutex is locked when QMutexLocker is created. You can unlock and relock the mutex with unlock() and relock() . If locked, the mutex will be unlocked when the QMutexLocker 被销毁。

例如,此复杂函数锁定 QMutex 当进入函数时并在所有退出点解锁互斥:

def complexFunction(flag):
    mutex.lock()
    retVal = 0
    if flag == 0 or flag == 1:
        mutex.unlock()
        return moreComplexFunction(flag)
    elif flag == 2:
        status = anotherFunction()
        if status < 0:
            mutex.unlock()
            return -2
        retVal = status + flag
    else:
        if flag > 10:
            mutex.unlock()
            return -1
    mutex.unlock()
    return retVal
											

此范例函数在开发过程中将变得更复杂,从而增加了发生错误的可能性。

使用 QMutexLocker greatly simplifies the code, and makes it more readable:

def complexFunction(flag):
    locker = QMutexLocker(mutex)
    retVal = 0
    if flag == 0 or flag == 1:
        return moreComplexFunction(flag)
    elif flag == 2:
            status = anotherFunction()
            if status < 0:
                return -2
            retVal = status + flag
    else:
        if flag > 10:
            return -1
    return retVal
											

Now, the mutex will always be unlocked when the QMutexLocker object is destroyed (when the function returns since locker 是自动变量)。

相同原理也适用于抛出、捕捉异常的代码。在锁定互斥的函数中未被捕获的异常没有办法解锁互斥,在把异常向上传递给调用函数的堆栈之前。

QMutexLocker also provides a mutex() member function that returns the mutex on which the QMutexLocker is operating. This is useful for code that needs access to the mutex, such as wait() 。例如:

class SignalWaiter:
    def __init__(mutex):
        self.locker = mutex
    def waitForSignal():
        # ...
        while not signalled:
            waitCondition.wait(self.locker.mutex())
        # ...
											
class QMutexLocker ( m )

QMutexLocker(m)

param m

QBasicMutex

构造 QMutexLocker and locks mutex 。互斥会被解锁 ( unlock() called) when the QMutexLocker is destroyed. If mutex is None , QMutexLocker does nothing.

另请参阅

lock()

PySide2.QtCore.QMutexLocker. __enter__ ( )
PySide2.QtCore.QMutexLocker. __exit__ ( arg__1 , arg__2 , arg__3 )
参数
  • arg__1 PyObject

  • arg__2 PyObject

  • arg__3 PyObject

PySide2.QtCore.QMutexLocker. mutex ( )
返回类型

QMutex

返回互斥在那里 QMutexLocker 正在运转。

PySide2.QtCore.QMutexLocker. relock ( )

重新锁定被解锁的互斥锁定器。

另请参阅

unlock()

PySide2.QtCore.QMutexLocker. unlock ( )

解锁此互斥锁定器。可以使用 relock() 以再次锁定它。它不需要被锁定当销毁时。

另请参阅

relock()