Qt 互斥量 QMutex

QMutex类提供了一种保护一个变量和一段代码的方法。

mutex.lock() //锁住互斥量(mutex)。如果互斥量是解锁的,那么当前线程就立即占用并锁定它。否则,当前线程就会被阻塞,知道掌握这个互斥量的线程对它解锁为止。

mutex.unlock()//解锁

mutex.tryLock()//尝试解锁,如果该互斥量已经锁住,它就会立即返回

For example, this complex function locks a QMutex upon entering the function and unlocks the mutex at all the exit points:

Cpp代码  收藏代码
  1. int complexFunction(int flag)  
  2.  {  
  3.      mutex.lock();  
  4.   
  5.      int retVal = 0;  
  6.   
  7.      switch (flag) {  
  8.      case 0:  
  9.      case 1:  
  10.          mutex.unlock();  
  11.          return moreComplexFunction(flag);  
  12.      case 2:  
  13.          {  
  14.              int status = anotherFunction();  
  15.              if (status < 0) {  
  16.                  mutex.unlock();  
  17.                  return -2;  
  18.              }  
  19.              retVal = status + flag;  
  20.          }  
  21.          break;  
  22.      default:  
  23.          if (flag > 10) {  
  24.              mutex.unlock();  
  25.              return -1;  
  26.          }  
  27.          break;  
  28.      }  
  29.   
  30.      mutex.unlock();  
  31.      return retVal;  
  32.  }  

 

This example function will get more complicated as it is developed, which increases the likelihood that errors will occur.

在一些复杂函数或时在抛出C++异常函数中锁定和解锁互定量,非常容易发生错误。Qt提供了方便的QMutexLocker类来简化对互斥量的处理。QMu特训Lock二的构造函数接受QMutex作为参数并且将其锁住。QMutexLock的析构函数则对这个互斥量进行解锁。

Using QMutexLocker greatly simplifies the code, and makes it more readable:

Cpp代码  收藏代码
  1. int complexFunction(int flag)  
  2.  {  
  3.      QMutexLocker locker(&mutex);  
  4.   
  5.      int retVal = 0;  
  6.   
  7.      switch (flag) {  
  8.      case 0:  
  9.      case 1:  
  10.          return moreComplexFunction(flag);  
  11.      case 2:  
  12.          {  
  13.              int status = anotherFunction();  
  14.              if (status < 0)  
  15.                  return -2;  
  16.              retVal = status + flag;  
  17.          }  
  18.          break;  
  19.      default:  
  20.          if (flag > 10)  
  21.              return -1;  
  22.          break;  
  23.      }  
  24.   
  25.      return retVal;  
  26.  }  

 

Now, the mutex will always be unlocked when the QMutexLocker object is destroyed (when the function returns since locker is an auto variable).

原文地址:https://www.cnblogs.com/lvdongjie/p/3758132.html