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:
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:
Now, the mutex will always be unlocked when the QMutexLocker object is destroyed (when the function returns since locker is an auto variable).
原文地址:http://www.cnblogs.com/lvdongjie/p/3758132.html