The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes. 更多...
| 頭: | #include <QMutexLocker> |
| qmake: | QT += core |
注意: 此類的所有函數 綫程安全 .
| QMutexLocker (QMutex * mutex ) | |
| ~QMutexLocker () | |
| QMutex * | mutex () const |
| void | relock () |
| void | unlock () |
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes.
鎖定和解鎖 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 當進入函數時並在所有退齣點解鎖互斥:
int complexFunction(int flag) { mutex.lock(); int retVal = 0; switch (flag) { case 0: case 1: retVal = moreComplexFunction(flag); break; case 2: { int status = anotherFunction(); if (status < 0) { mutex.unlock(); return -2; } retVal = status + flag; } break; default: if (flag > 10) { mutex.unlock(); return -1; } break; } mutex.unlock(); return retVal; }
此範例函數在開發過程中將變得更復雜,從而增加瞭發生錯誤的可能性。
使用 QMutexLocker greatly simplifies the code, and makes it more readable:
int complexFunction(int flag) { QMutexLocker locker(&mutex); int retVal = 0; switch (flag) { case 0: case 1: return moreComplexFunction(flag); case 2: { int status = anotherFunction(); if (status < 0) return -2; retVal = status + flag; } break; default: if (flag > 10) return -1; break; } 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
QWaitCondition::wait
()。例如:
class SignalWaiter { private: QMutexLocker locker; public: SignalWaiter(QMutex *mutex) : locker(mutex) { } void waitForSignal() { ... while (!signalled) waitCondition.wait(locker.mutex()); ... } };
另請參閱 QReadLocker , QWriteLocker ,和 QMutex .
構造 QMutexLocker 和鎖 mutex . The mutex will be unlocked when the QMutexLocker 被銷毀。若 mutex 為 0, QMutexLocker 什麼都不做。
另請參閱 QMutex::lock ().
銷毀 QMutexLocker 並解鎖在構造函數中被鎖定的互斥。
另請參閱 QMutex::unlock ().
返迴互斥在那裏 QMutexLocker 正在運轉。
重新鎖定被解鎖的互斥鎖定器。
另請參閱 unlock ().
解鎖此互斥鎖定器。可以使用
relock()
以再次鎖定它。它不需要被鎖定當銷毀時。
另請參閱 relock ().