博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
QMutex 的简单案例
阅读量:7165 次
发布时间:2019-06-29

本文共 2599 字,大约阅读时间需要 8 分钟。

#ifndef MYDIALOG_H#define MYDIALOG_H#include"mythread.h"#include
#include
#include
#include
class MyDialog : public QWidget{ Q_OBJECTpublic: 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 
#include
class myThread : public QThread{ Q_OBJECTpublic: myThread(QObject *parent=0); virtual void run(); bool Stop; bool needQuit;signals: void NumberChanged(int);};#endif // MYTHREAD_H
myThread.h
#include "mydialog.h"#include 
#include
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

 

转载于:https://www.cnblogs.com/TadGuo/p/9016499.html

你可能感兴趣的文章