本文参考了《Qt Creator快速入门》中的代码和讲解,若本文未能解答你的问题,请自行查阅书籍和相关资料;
QT提供了对线程的支持,这使得我们在多线程编程中可以有效的解决在不冻结当前应用程序用户界面的情况下执行其他操作。
在这里我整理出了一些关于QThread的常用函数和信号
volatile 它是被设计用来修饰被不同线程访问和修改的变量。
##QThread 要创建一个线程类,需要子类化QThread并重新实现run()函数
静态函数:
-currentThreadId(); 返回系统特定的ID
-currentThread(); 返回QThread指针
-sleep(); 精度为秒
-msleep(); 精度为毫秒
-usleep(); 精度为微秒
函数:
-start(); 默认调用run函数,开始执行该线程;
-run(); 类似于main()函数;
-isFinished(); -isRunning(); 查询线程状态
-setStackSize(); 设置一个自定义的堆栈大小,不用的话操作系统给默认
-exec(); 启动事件循环
-exit(); -quit(); 停止事件循环
信号:
-started(); 线程开始时触发
-finished(); 线程结束时触发
-terminated(); 线程终止时
要学会如何多线程编程,首先我们应该熟悉并掌握单个线程的编写,下面给出一个线程类的经典写法:
//单个线程编写
class MyThread : public QThread
{
protected:
void run();
};
void MyThread::run() //重写
{
/*执行代码*/
exec();
}
int main(int argc,char *argv[])
{
QCoreApplication a(argc,argv);
MyThread thread1;
thread1.start(); //自动调用run();
return a.exec();
}
接下来我们实现两个线程的编写:
//两个线程编写
class myThread : public QThread
{
public:
myThread(QString strdate);
void stop();
public:
int count=0;
protected:
void run();
private:
volatile bool stopped; //volatile它是被设计用来修饰被不同线程访问和修改的变量。
QString str;
};
myThread::myThread(QString strdate)
{
stopped = false;
str = strdate;
}
void myThread::stop()
{
stopped = true;
}
void myThread::run()
{
while(!stopped)
{
qDebug() << str ;
count++;
}
stopped = false;
}
int main(int argc,char *argv[])
{
QCoreApplication a(argc,argv);
myThread thread1("thread1");
myThread thread2("thread2");
thread1.start(); //默认调用run();
thread2.start();
while(thread1.count < 100);
thread1.stop();
while(thread2.count <150);
thread2.stop();
thread1.wait(); //等待线程结束
thread2.wait();
return a.exec();
}