QT开发之多线程

在Linux中我们经常使用多线程编程,同时就会提出同步和异步操作.像原子变量,信号量,阻塞,自旋锁,互斥所等,在Qt中也有类似的概念,但是在我的开发中用的不是很多,下面列举一下多线程编程的基础.


新建一个Gui应用项目,代码注释的非常详细.

创建线程后,启动线程默认是run函数,除非有特殊指定


dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QThread>

namespace Ui {
class Dialog;
}

class MyThread : public QThread
{
    Q_OBJECT
public:
    explicit MyThread(QObject *parent = 0);
    void stop();

protected:
    void run();

private:
    volatile bool stopped;
    int shareValue;

signals:

public slots:

};

class Dialog : public QDialog
{
    Q_OBJECT
    
public:
    explicit Dialog(QWidget *parent = 0);
    ~Dialog();
    
private slots:
    void on_startButton_clicked();

    void on_stopButton_clicked();

    void on_startButton_2_clicked();

    void on_stopButton_2_clicked();

private:
    Ui::Dialog *ui;
    MyThread thread1,thread2;
};

#endif // DIALOG_H

dialog.cpp

#include "dialog.h"
#include "ui_dialog.h"
#include <QDebug>

/* A B线程共同去访问某一资源测试 */

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    //connect(&thread1,SIGNAL(started()),this,SLOT(startThread1()));
    //connect(&thread1,SIGNAL(finished()),this,SLOT(stopThread1()));
}

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


MyThread::MyThread(QObject *parent) : /* 构造函数 */
    QThread(parent)
{
    stopped = false;
    shareValue = 0;
}

void MyThread::run()  /* start()函数默认会调用run()函数 */
{
    //int i = 0;
    while (!stopped){
        //qDebug() << QString("in MyThread: %1").arg(i++);
        msleep(1000);
        qDebug() << "shareValue" << shareValue++ << endl;
        //i++;
    }

    stopped = false;
}

void MyThread::stop()
{
    stopped = true;
}

/* A线程操作 */
void Dialog::on_startButton_clicked()
{
    thread1.start();
    //thread.wait()   /* 同步终止 */
    ui->startButton->setEnabled(false);
    ui->stopButton->setEnabled(true);
    //int Thread = thread1.currentThreadId();
}

void Dialog::on_stopButton_clicked()
{
    if(thread1.isRunning()){
        thread1.stop();
        ui->startButton->setEnabled(true);
        ui->stopButton->setEnabled(false);
    }
}


/* B 线程操作 */
void Dialog::on_startButton_2_clicked()
{
    thread2.start();
    //thread.wait()   /* 同步终止 */
    ui->startButton_2->setEnabled(false);
    ui->stopButton_2->setEnabled(true);
}

void Dialog::on_stopButton_2_clicked()
{
    if(thread2.isRunning()){
        thread2.stop();
        ui->startButton_2->setEnabled(true);
        ui->stopButton_2->setEnabled(false);
    }
}


界面效果:


已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页