Qt QMutexLocker_自動解鎖的機制


QMutexLocker 是一個便利類,它可以自動對QMutex加鎖與解鎖。因為QMutexLocker 申請的這個lock變量在這個函數退出時,自動的調用析構函數來解鎖。這樣可以防止在程序編寫的過程中,不同的地方有多個return的情況,在發生return的時候,沒有解鎖,導致程序死鎖。
下面是一個例子,分別使用了以上兩個類。

第一、使用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;
  } 

第二、使用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;
  }
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM