QT QMutex简介(QT多线程编程一)
QMutex简介
QMutex类提供了一种保护一个变量或者一段代码的方法,这样可以每次只让一个线程访问它。这个类提供了一个lock()函数用于锁住互斥量,如果互斥量是解锁状态,那么当前线程立即占用并锁定它;否则,当前线程会阻塞,直到这个互斥量的线程对它解锁为止。QMutex类还提供了一个tryLock()函数,如果该互斥量已经锁定,它就会立即返回。
[cpp]view plaincopy
#include<QCoreApplication>
#include<stdio.h>
#include<QThread>
#include<QMutex>
//
classMutexThread:publicQThread
{
public:
MutexThread();
voidstop();
private:
boolflgRunning;
QMutexmutex;
voidrun();
};
MutexThread::MutexThread()
{
flgRunning=true;
}
voidMutexThread::stop()
{
mutex.tryLock();
flgRunning=false;
mutex.unlock();
}
voidMutexThread::run()
{
mutex.tryLock();
while(flgRunning==true)
{
printf("Hello,World!\n");
sleep(1);
}
mutex.unlock();
printf("ThreadExit!\n");
}
//
intmain(intargc,char**argv)
{
QCoreApplicationcapp(argc,argv);
MutexThreadmThread;
mThread.start();
while(1)
{
if(getchar()=='B')
{
mThread.stop();
mThread.wait();
break;
}
}
returncapp.exec();
}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。