QMutex 的简单案例

#ifndef MYDIALOG_H
#define MYDIALOG_H

#include"mythread.h"
#include<QPushButton>
#include<QLabel>
#include<QHBoxLayout>
#include <QString>

class MyDialog : public QWidget
{
    Q_OBJECT

public:

    MyDialog(QWidget *parent = 0);
    ~MyDialog();
    void closeEvent(QCloseEvent *e);
private:
    myThread *mThread;
    QPushButton *startBtn;
    QPushButton *stopBtn;
    QLabel *label;
public slots:
    void onNumberChanged(int);
    void startBtn_click();
    void stopBtn_click();
};

#endif // MYDIALOG_H
MyDialog.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QMutex>
#include<QThread>

class myThread : public QThread
{
    Q_OBJECT
public:
    myThread(QObject *parent=0);
    virtual void run();
    bool Stop;
    bool needQuit;
signals:
    void NumberChanged(int);

};

#endif // MYTHREAD_H
myThread.h
#include "mydialog.h"
#include <QCloseEvent>
#include <QDebug>
MyDialog::MyDialog(QWidget *parent)
    : QWidget(parent)
{
    startBtn = new QPushButton("Start");
    stopBtn = new QPushButton("Stop");
    label = new QLabel;
    label->setText("Number");

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(label);
    layout->addSpacing(20);
    layout->addWidget(startBtn);
    layout->addWidget(stopBtn);
    setLayout(layout);

    mThread = new myThread(this);

    QObject::connect(mThread, SIGNAL(NumberChanged(int)), this, SLOT(onNumberChanged(int)));
    QObject::connect(startBtn, SIGNAL(clicked()), this, SLOT(startBtn_click()));
    QObject::connect(stopBtn, SIGNAL(clicked()), this, SLOT(stopBtn_click()));
}

MyDialog::~MyDialog()
{

}

void MyDialog::onNumberChanged(int number)
{
    label->setText(QString::number(number));
}

void MyDialog::startBtn_click()
{
    mThread->Stop = false;
    mThread->start();
}

void MyDialog::stopBtn_click()
{
    mThread->Stop = true;
}

void MyDialog::closeEvent(QCloseEvent *e){
    mThread->needQuit = true;
    qDebug() << "close event";
    mThread->requestInterruption();
    mThread->Stop = false;
    mThread->wait(1001);
    mThread->exit();
mydialog.cpp
#include "mythread.h"

myThread::myThread(QObject*parent):QThread(parent)
{
    needQuit = false;
}

void myThread::run()
{
    for (int i= 0; i < 1000; i++)
    {
        QMutex mutex;
        mutex.lock();
        if(this->Stop)
        {
            while(1){
                if(!this->Stop)
                    break;
            }
        }
        if(needQuit){
            mutex.unlock();
            return;
        }

        mutex.unlock();


        emit NumberChanged(i);
        msleep(100);

    }

}
myThread.cpp

 

posted @ 2018-05-09 20:41  Bear_Guo  阅读(812)  评论(0编辑  收藏  举报