工作需要,前段时间要写TCP连接的模块,因为连接本身可能是一个耗时的操作,而且要实现自动重连功能,所以必须要用到多线程,因此有机会学习QThread,现将体会成文。
首先是QThread::exec(),这个函数将进入当前线程的事件循环(网上很多文章都写成时间循环),调用这个函数后将会阻塞线程,这时线程中的事件传递才有效,信号与槽的连接才有效,此时信号发射后槽函数才会被调用。当执行了线程的quit()或exit()函数时exec()函数才返回。
看程序
//mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
class QTimer ;
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = 0);
protected:
void run();
public slots:
void slotFunc();
private:
QTimer *timer;
};
#endif // MYTHREAD_H
//mythread.cpp
#include "mythread.h"
#include <QtDebug>
#include <QTimer>
MyThread::MyThread(QObject *parent) :
QThread(parent)
{
}
void MyThread::run()
{
timer = new QTimer;
timer->setSingleShot(true);
timer->start(5000);
qDebug() << timer << QThread::currentThreadId();
connect(timer, SIGNAL(timeout()), this, SLOT(slotFunc()));
exec();
qDebug() << "********************";
}
void MyThread::slotFunc()
{
qDebug() << timer << QThread::currentThreadId();
qDebug() << "#################";
}
//main.cpp
#include <QApplication>
#include "mythread.h"
int main(int argc, c