QT中的多线程(一)

问题描述:

现在有这样一个计时器,它需要一边走动,一边计算一个复杂度很高的计算(需要5秒),但是单线程的时候,这个5秒的计算会堵住,导致线路阻塞,所以我们需要两条线路

mythread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QThread>

class myThread : public QThread
{
    Q_OBJECT
public:
    explicit myThread(QObject *parent = nullptr);
protected:
    void run();//线程处理的虚函数
               //不能直接调用,通过start调用
signals:
    void isdone();
public slots:

};

#endif // MYTHREAD_H

run()函数是这个线程需要做的事情

isdone是判断是否完成工作的信号

mythread.cpp

#include "mythread.h"

myThread::myThread(QObject *parent) : QThread(parent)
{

}
void myThread::run()
{
    //处理一个复杂的数据,需要耗时5秒
    sleep(5);
    emit isdone();
}

用sleep表示一个5秒的计算

计算完以后就触发isdone信号

mywidget.h

#ifndef MYWIDGET_H
#define MYWIDGET_H

#include <QWidget>
#include<QTimer>
#include"mythread.h"
namespace Ui {
class myWidget;
}

class myWidget : public QWidget
{
    Q_OBJECT

public:
    explicit myWidget(QWidget *parent = 0);
    void dealTimer();/让计时器走起来
    void endTimer();//结束计时器
    void stopThread();//停止线程
    ~myWidget();

private slots:
    void on_pushButton_clicked();

private:
    Ui::myWidget *ui;
    QTimer *timer;
    myThread *thread;//创建线程对象
};

#endif // MYWIDGET_H

mywidget.cpp

#include "mywidget.h"
#include "ui_mywidget.h"

myWidget::myWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::myWidget)
{
    ui->setupUi(this);
    timer=new QTimer(this);
    connect(timer,&QTimer::timeout,this,&myWidget::dealTimer);
    thread=new myThread(this);
    connect(thread,&myThread::isdone,this,&myWidget::endTimer);
    connect(this,&myWidget::destroy,this,&myWidget::stopThread);//当关闭窗口的时候,就会调用关闭线程的函数
}
void myWidget::endTimer()
{
    timer->stop();
}
void myWidget::stopThread()//停止线程函数
{
    //停止线程
    thread->quit();
    //等待线程处理完手头的工作
    thread->wait();
}
void myWidget::dealTimer()
{
    static int i=0;
    i++;
    ui->lcdNumber->display(i);
}
myWidget::~myWidget()
{
    delete ui;
}

void myWidget::on_pushButton_clicked()
{
    if(timer->isActive()==false)
    {
        timer->start(1000);
    }
    //启动线程
    thread->start();
}

一旦接收到isdone信号后就会调用endTimer函数

注意一些新知识:

1.QT中创建一个线程就是再创建一个类,再创建一个对象

2.thread.quit    这是停止线程的函数

3.thread.wait   等待线程把所有工作完成以后再关闭

4.thread.start  这是间接调用函数run,但是必须这样驱动线程,不能直接调用run函数

猜你喜欢

转载自blog.csdn.net/scwMason/article/details/81322680