当前位置: 首页 > >

QT??QMutex(互斥量)

发布时间:

互斥:mutex只允许某个时刻只允许一个线程对共享资源进行访问


加入头文件:


#include


它的函数:


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


看个例子:

QMutex mutex;
int number = 6;

void method1()
{
mutex.lock();
number *= 5;
number /= 4;
mutex.unlock();
}

void method2()
{
mutex.lock();
number *= 3;
number /= 2;
mutex.unlock();
}

下面说一下互斥模式:

enumQMutex::RecursionMode


ConstantValueDescription
QMutex::Recursive1一个线程可对同一个互斥量加锁多次,并且只有对应的解锁才能释放一个互斥量
QMutex::NonRecursive0一个线程只能锁住一个互斥量

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 constructorvoid relock ()//Relocks an unlocked mutex lockervoid unlock ()//Unlocks this mutex locker. You can userelock() to lock it again. It does not need to be lockedwhen destroyed

int complexFunction(int flag)

{

?

???mutex.lock();

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

????mutex.unlock();
????return retVal;
}


int complexFunction(int flag)
{
?


???QMutexLocker locker(&mutex);
?


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



?

?
?
?
?
return retVal;

}





友情链接: