十三、Qt多线程与线程安全-一、多线程程序

时间:2024-03-05 14:18:00
QThread类提供了管理线程的方法:
  • 一个对象管理一个线程
  • 一般从QThread继承一个自定义类,重载run函数

1、实现程序

在这里插入图片描述

(1)创建项目,基于QDialog

(2)添加类,修改基于QThread

在这里插入图片描述

#ifndef DICETHREAD_H
#define DICETHREAD_H

#include <QThread>

class DiceThread : public QThread
{
    Q_OBJECT

private:
    int m_seq = 0;
    int m_diceValue;
    bool m_Paused = true;
    bool m_stop = false;

public:
    explicit DiceThread();

    void diceBegin();
    void dicePause();
    void stopThread();

protected:
    void run() Q_DECL_OVERRIDE;

signals:
    void newValued(int seq, int diceValue);

public slots:
};

#endif // DICETHREAD_H
#include "dicethread.h"
#include <QTime>

DiceThread::DiceThread()
{

}

void DiceThread::diceBegin()
{
    m_Paused = false;
}

void DiceThread::dicePause()
{
    m_Paused = true;
}

void DiceThread::stopThread()
{
    m_stop = true;
}

void DiceThread::run()
{
    m_stop = false;
    m_seq = 0;
    qsrand(QTime::currentTime().second());
    while (!m_stop) {
        if(!m_Paused)
        {
            m_diceValue = qrand()%6+1;
            m_seq++;
            emit newValued(m_seq, m_diceValue);
        }
        sleep(1);
    }
    quit();
}

(3)实现按钮功能

#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    ui->btnStartThread->setEnabled(true);
    ui->btnStart->setEnabled(false);
    ui->btnStop->setEnabled(false);
    ui->btnStopThread->setEnabled(false);

    connect(&threadA, SIGNAL(started()),
            this, SLOT(on_threadAStarted()));
    connect(&threadA, SIGNAL(finished()),
            this, SLOT(on_threadAFinished()));
    connect(&threadA, SIGNAL(newValued(int,int)),
            this, SLOT(on_threadAnewValue(int,int)));
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::closeEvent(QCloseEvent *event)
{
    if(threadA.isRunning())
    {
        threadA.stopThread();
        threadA.wait();
    }
    event->accept();
}

void Dialog::on_btnStartThread_clicked()
{
    threadA.start();
}

void Dialog::on_btnStart_clicked()
{
    threadA.diceBegin();
}

void Dialog::on_btnStop_clicked()
{
    threadA.dicePause();
}

void Dialog::on_btnStopThread_clicked()
{
    threadA.stopThread();
}

void Dialog::on_btnClearText_clicked()
{
    ui->plainTextEdit->clear();
}

void Dialog::on_threadAnewValue(int seq, int diceValue)
{
    ui->plainTextEdit->appendPlainText(QString::asprintf("第%d次投色子: 点数%d", seq, diceValue));
}

void Dialog::on_threadAStarted()
{
    ui->labelStatus->setText("Thread状态:started");
    ui->btnStartThread->setEnabled(false);
    ui->btnStart->setEnabled(true);
    ui->btnStop->setEnabled(true);
    ui->btnStopThread->setEnabled(true);
}

void Dialog::on_threadAFinished()
{
    ui->labelStatus->setText("Thread状态:finished");
    ui->btnStartThread->setEnabled(true);
    ui->btnStart->setEnabled(false);
    ui->btnStop->setEnabled(false);
    ui->btnStopThread->setEnabled(false);
}

在这里插入图片描述