PySide.QtCore.QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes.
锁定和解锁 PySide.QtCore.QMutex in complex functions and statements or in exception handling code is error-prone and difficult to debug. PySide.QtCore.QMutexLocker can be used in such situations to ensure that the state of the mutex is always well-defined.
PySide.QtCore.QMutexLocker should be created within a function where a PySide.QtCore.QMutex needs to be locked. The mutex is locked when PySide.QtCore.QMutexLocker is created. You can unlock and relock the mutex with unlock() and relock() . If locked, the mutex will be unlocked when the PySide.QtCore.QMutexLocker 被销毁。
例如,此复杂函数锁定 PySide.QtCore.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
此范例函数在开发过程中将变得更复杂,从而增加了发生错误的可能性。
使用 PySide.QtCore.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 PySide.QtCore.QMutexLocker object is destroyed (when the function returns since locker 是自动变量)。
相同原理也适用于抛出、捕捉异常的代码。在锁定互斥的函数中未被捕获的异常没有办法解锁互斥,在把异常向上传递给调用函数的堆栈之前。
PySide.QtCore.QMutexLocker also provides a mutex() member function that returns the mutex on which the PySide.QtCore.QMutexLocker is operating. This is useful for code that needs access to the mutex, such as QWaitCondition.wait() 。例如:
class SignalWaiter:
def __init__(mutex):
self.locker = mutex
def waitForSignal():
# ...
while not signalled:
waitCondition.wait(self.locker.mutex())
# ...
| 参数: | m – PySide.QtCore.QMutex |
|---|
构造 PySide.QtCore.QMutexLocker and locks mutex . The mutex will be unlocked when the PySide.QtCore.QMutexLocker is destroyed. If mutex is zero, PySide.QtCore.QMutexLocker does nothing.
另请参阅
| 参数: |
|
|---|
| 返回类型: | PySide.QtCore.QMutex |
|---|
Returns a pointer to the mutex that was locked in the constructor.
重新锁定被解锁的互斥锁定器。
解锁此互斥锁定器。可以使用 relock() 以再次锁定它。它不需要被锁定当销毁时。