QT——QMutex(互斥量)

时间:2025-01-18 22:33:28
互斥:mutex只允许某个时刻只允许一个线程对共享资源进行访问

加入头文件:

#include<QMutex>

它的函数:

  • QMutex( RecursionModemode = NonRecursive )
  • ~QMutex ()
  • void lock()//锁定互斥量,若有一个线程已经锁定了这个互斥量,这次的调用将阻塞直到那个线程把它解锁才行
  • bool tryLock()//试图加锁,若有线程在使用则返回false,不会被阻塞
  • bool tryLock( inttimeout )//在timeout时间内试图加锁
  • void unlock()//解锁

看个例子:
 QMutex mutex;
 int number = 6;

 void method1()
 {
     ();
     number *= 5;
     number /= 4;
     ();
 }

 void method2()
 {
     ();
     number *= 3;
     number /= 2;
     ();
 }
下面说一下互斥模式:

enumQMutex::RecursionMode

 
 
Constant Value Description
QMutex::Recursive 1 一个线程可对同一个互斥量加锁多次,并且只有对应的解锁才能释放一个互斥量
QMutex::NonRecursive 0 一个线程只能锁住一个互斥量
QMutex *mutex=new QMutex(QMutex::Recursive);//默认是NonRecursive 


QMutexLocker

它的函数:

  • QMutexLocker( QMutex *mutex )
  • ~QMutexLocker()
  • QMutex * mutex () const//Returns a pointer to the mutex that waslocked in the constructor
  • void relock ()//Relocks an unlocked mutex locker
  • void unlock ()//Unlocks this mutex locker. You can userelock() to lock it again. It does not need to be lockedwhen destroyed

int complexFunction(int flag)
{
 

   ();

    int retVal = 0;
    //.....

    ();
    return retVal;
}

int complexFunction(int flag)
{
 

   QMutexLocker locker(&mutex);
 

   int retVal = 0;
    //.....


 
        return retVal;
}