QMutexLockerclass is a convenience class that simplifies locking and unlocking mutexes. 更多 …
锁定和解锁
QMutexin complex functions and statements or in exception handling code is error-prone and difficult to debug.QMutexLockercan be used in such situations to ensure that the state of the mutex is always well-defined.
QMutexLockershould be created within a function where aQMutexneeds to be locked. The mutex is locked whenQMutexLockeris created. You can unlock and relock the mutex withunlock()andrelock(). If locked, the mutex will be unlocked when theQMutexLocker被销毁。例如,此复杂函数锁定
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此范例函数在开发过程中将变得更复杂,从而增加了发生错误的可能性。
使用
QMutexLockergreatly 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 retValNow, the mutex will always be unlocked when the
QMutexLockerobject is destroyed (when the function returns sincelocker是自动变量)。相同原理也适用于抛出、捕捉异常的代码。在锁定互斥的函数中未被捕获的异常没有办法解锁互斥,在把异常向上传递给调用函数的堆栈之前。
QMutexLockeralso provides amutex()member function that returns the mutex on which theQMutexLockeris operating. This is useful for code that needs access to the mutex, such aswait()。例如:class SignalWaiter: def __init__(mutex): self.locker = mutex def waitForSignal(): # ... while not signalled: waitCondition.wait(self.locker.mutex()) # ...
QMutexLocker
(
m
)
¶
QMutexLocker(m)
- param m
构造
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
(
)
¶
返回互斥在那里
QMutexLocker
正在运转。