QMutexLocker 是一個便利類,它能夠自動對QMutex加鎖與解鎖。由於QMutexLocker 申請的這個lock變量在這個函數退出時,自動的調用析構函數來解鎖。這樣能夠防止在程序編寫的過程當中,不一樣的地方有多個return的狀況,在發生return的時候,沒有解鎖,致使程序死鎖。
下面是一個例子,分別使用了以上兩個類。html
第1、使用QMutex
int complexFunction(int flag)
{
mutex.lock();
int retVal = 0;
switch (flag) {
case 0:
case 1:
mutex.unlock();
return moreComplexFunction(flag);
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;
}
第2、使用QMutexLocker
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;
}