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:

 

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;
 }
 

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:

 

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 is an auto variable).

 

你可能感兴趣的:(qt,互斥,QMutex)