一、简单的使用线程
如何使用线程呢?通过继承QThread类,重载void run()函数,之后调用start函数启动线程即可
#include <QCoreApplication>
#include <QThread>
#include <QDebug>
class MyThread : public QThread
{
protected:
void run()
{
for(int i=0; i<5; i++)
{
qDebug() << objectName() << " : " << i;
sleep(1);
}
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyThread t;
t.setObjectName("t");
t.start();
MyThread tt;
tt.setObjectName("tt");
tt.start();
return a.exec();
}
二、线程增加开启和关闭线程标志位
class Sample : public QThread
{
protected:
volatile bool m_toStop;
void run()
{
int* p = new int[10000];
for(int i=0; !m_toStop && (i<10); i++)
{
qDebug() << objectName() << " : " << i;
p[i] = i * i * i;
msleep(500);
}
delete[] p; //内存泄漏
qDebug() << objectName() << " : end";
}
public:
Sample()
{
m_toStop = false;
}
void stop()
{
m_toStop = true;
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug() << "main begin";
Sample t;
t.setObjectName("t");
t.start();
//for(int i=0; i<10000; i++)
//{
// for(int j=0; j<10000; j++)
// {
//}
//}
msleep(500*10);
t.stop(); //执行后无内存泄漏
//t.terminate(); //会在线程未结束时,杀死线程, 内存泄漏
qDebug() << "main end";
return a.exec();
}
三、生产者和消费者的一个例子
#include <QCoreApplication>
#include <QThread>
#include <QDebug>
#include <QMutex>
static QString g_store;
static QMutex g_mutex;
class Producer : public QThread
{
protected:
void run()
{
int count = 0;
while (true)
{
g_mutex.lock();
g_store.append(QString::number((count++) % 10)); //将随机数字(0-9)存入仓库
qDebug() << objectName() << " : " + g_store;
g_mutex.unlock();
msleep(1);
}
}
};
class Customer : public QThread
{
protected:
void run()
{
while (true)
{
g_mutex.lock();
if( g_store != "")
{
g_store.remove(0, 1);
qDebug() << objectName() << " : " + g_store;
}
g_mutex.unlock();
msleep(1);
}
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Producer p;
Customer c;
p.setObjectName("Producer");
c.setObjectName("Customer");
p.start();
c.start();
return a.exec();
}