1.重写QThread 的run()函数
class MyThread : public QThread
{
protected:
void run();
}
void MyThread::run()
{
m_isCanRun = true;//标记可以运行
//希望线程处理的事情
QMutexLocker locker(&m_lock);// 此处加锁,防止访问冲突
if(!m_isCanRun)//在每次循环判断是否可以运行,如果不行就退出循环
{
return;
}
}
main
{
MyThread thread;
thread.start();
//子线程指针,尽量不要去delete ,这样不安全。一般会绑定QObject::deleteLater()方法。
connect(thread,&QThread::finished ,thread,&QObject::deleteLater);
}
2.QObject::movetoThread()函数
class Worker:public QObjiec
{
Q_OBJECT
public slots:
void dowork()
{
//do work
emit dealResault(resault);
}
signals:
void dealResault(const QString &resault);
}
class Controllre: public QObject
{
Q_OBJECT
public:
QThread workThread();
Controllre()
{
WorkerObj *worker = new WorkerObj;
worker->movetoThread(&workThread);
connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater); //这个信号槽必须连接,否则会内存泄漏
connect(&workerThread,SIGNALS(started()),worker,SLOT(doWork()));
workThread.start();
connect(worker,SIGNAL(dealResault(QString)),this,SLOT(resault(QString)));
}
~controllre()
{
workThread.quit();
workerThread.wait();
}
public slots:
void resault(QString &data);
}