QT多线程创建的误区:run函数
直接上代码吧,注意这种方法创建的多线程,只有run函数内的属于新的线程,OnTempTimer()虽然是run函数调用的,但是是主线程在执行,一定要注意啊。这样弄相当于没有任何意义,还是主线程在处理函数。
下一个博客有讲怎么实现多线程的正确创建和使用
MainWindow.cpp
MysqlThread = new ReconnectMysql();
MysqlThread->start();
reconnectmysql.cpp
#include "reconnectmysql.h"
ReconnectMysql::ReconnectMysql()
{
}
void ReconnectMysql::run()
{
qDebug()<< "run()";
//Timer = new QTimer(this);这样写会报错:
//Parent is ReconnectMysql(0xd621978), parent's thread is QThread(0x4ac5dd0),
//current thread is ReconnectMysql(0xd621978)
Timer = new QTimer();//或者Timer = new QTimer(NULL);
//这句话也要在run()不能像这样给定时器指定父对象 Timer = new QTimer(this);
Timer->start(1000);
connect(Timer, SIGNAL(timeout()), this, SLOT(OnTempTimer()));
this->exec();//不加这句话定时器不执行
}
void ReconnectMysql::OnTempTimer()
{
qDebug()<< "OnTempTimer()";
}
reconnectmysql.h 注意继承的QThread
#ifndef RECONNECTMYSQL_H
#define RECONNECTMYSQL_H
#include <QObject>
#include <QThread>
#include <QTimer>
#include <QDebug>
class ReconnectMysql : public QThread
{
Q_OBJECT
public:
explicit ReconnectMysql();
void run();
signals:
public slots:
void OnTempTimer();
private:
QTimer *Timer;
};
#endif // RECONNECTMYSQL_H
打印:
怎么验证以上的说法呢,很简单,用这个函数QThread::currentThreadId();获取当前线程的ID
qDebug()<<tr("主线程id:")<<QThread::currentThreadId();
//多线程方式1
myThread = new MyThread();
myThread->start();
void MyThread::run()//只有run()里面在新的线程里
{
qDebug()<<tr("mythread QThread::currentThreadId()==")<<QThread::currentThreadId();
//这种方式还是相当于在主线程里面执行
timer= new QTimer(NULL);
connect(timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
timer->start(1000);
this->exec();
}
//这种方式还是相当于在主线程里面执行
void MyThread::onTimeout()
{
qDebug()<<tr("mythread QThread::currentThreadId()==")<<QThread::currentThreadId();
qDebug()<<"globalCount: " << ++globalCount;
}
还没有评论,来说两句吧...