自学内容网 自学内容网

QT中多线程使用(二)

https://subingwen.cn/qt/thread/#1-%E7%BA%BF%E7%A8%8B%E7%B1%BB-QThread
https://www.bilibili.com/video/BV1iN411f7dY?buvid=XU932919AEC08339E30CE57D39A2BABF6A44F&from_spmid=search.search-result.0.0&is_story_h5=false&mid=rSmqqQLB5PQj7nof4wjfpQ%3D%3D&plat_id=114&share_from=ugc&share_medium=android&share_plat=android&share_session_id=a01714b7-a97c-4ec7-8dbb-548099f05c05&share_source=WEIXIN&share_source=weixin&share_tag=s_i&spmid=united.player-video-detail.0.0&timestamp=1737024828&unique_k=gr9tHaA&up_id=147020887&vd_source=b3723521e243814388688d813c9d475f&spm_id_from=333.788.player.switch&p=7

一.流程:
1.先创建一个类,这个类从QObject继承得到。
2.在这个类中添加一个公共的成员函数,函数体就是我们在子线程中执行的业务逻辑。
3.在主线程中创建一个QThread对象,这就是子线程的对象。
4.在主线程中创还能工作的类对象(千万不要给创建的对象指定父对象)
5.将工作对象移动到创建的子线程对象中,需要调用QObject类提供的moveToThread方法。
6.启动子线程,调用start(),这时候线程启动了,但是移动到线程中的对象并没有工作。
7.调用工作对象的工作函数,让这个函数开始执行,这时候是在移动到的那个子线程中运行的。
二. 示例
让工作对象类继承QObject

#pragma once
#include <QObject>
class Generate:public QObject
{
    Q_OBJECT
public:
    explicit Generate(QObject* parent = nullptr);

    void working(int num);
signals:
    void sendArray(QVector<int> num);
private:
    int m_num;
};


#include "Generate.h"
#include <QDebug>
#include <QVector>
#include <QElapsedTimer>
#include <QRandomGenerator>
#include <QThread>

Generate::Generate(QObject* parent) 
    : QObject{ parent }
{}


void Generate::working(int num)
{
    //生成m_num个随机数
    qDebug() << "生成随机数的线程的线程地址是:" << QThread::currentThread();
    QVector<int> list;
    //list.resize(m_num);
    //统计生成这些随机数所消耗的时间
    QElapsedTimer time;
    time.start();
    for (int i = 0; i < num; i++)
    {
        list.push_back(QRandomGenerator::global()->bounded(10000));
    }
    int milsec = time.elapsed();
    qDebug() << "生成" << num << "个随机数总共耗时" << QString::number(milsec);
    //生成完随即数后发送信号告诉主线程可以使用这些数据了
    emit sendArray(list);
}

#pragma once
#include <QObject>
#include <QVector>
class BubbleSort : public QObject
{
    Q_OBJECT
public:
    explicit BubbleSort(QObject* parent = nullptr);

    void working(QVector<int> list);
signals:
    void finish(QVector<int> list);
};


#include "BubbleSort.h"
#include <QDebug>
#include <QElapsedTimer>
#include <QThread>

BubbleSort::BubbleSort(QObject* parent)
    : QObject(parent)
{

}


void BubbleSort::working(QVector<int> list)
{
    qDebug() << "bubble sort thread address is:" << QThread::currentThread();
    QElapsedTimer time;
    time.start();
    int temp;
    for (int i = 0; i < list.size(); ++i)
    {
        for (int j = 0; j < list.size() - i - 1; ++j)
        {
            if (list[j] > list[j + 1])
            {
                temp = list[j];
                list[j] = list[j + 1];
                list[j + 1] = temp;
            }
        }
    }
    int milsec = time.elapsed();
    qDebug() << "bubble sort time is " << milsec << "ms";
    emit finish(list);
}

#pragma once
#include <QObject>
#include <QVector>
class QuickSort : public QObject
{
    Q_OBJECT
public:
    explicit QuickSort(QObject* parent = nullptr);

    void working(QVector<int> list);
private:
    void quickSort(QVector<int>& list, int l, int r);
signals:
    void finish(QVector<int> list);
};




#include "QuickSort.h"
#include <QDebug>
#include <QElapsedTimer>
#include <QThread>
QuickSort::QuickSort(QObject* parent)
    : QObject(parent)
{}


void QuickSort::working(QVector<int> list)
{
    qDebug() << "quick sort thread address is :" << QThread::currentThread();
    QElapsedTimer time;
    time.start();
    quickSort(list, 0, list.size() - 1);
    int milsec = time.elapsed();
    qDebug() << "quick sort time is" << milsec << "ms";
    emit finish(list);
}

void QuickSort::quickSort(QVector<int>& s, int l, int r)
{
    if (l < r)
    {
        int i = l, j = r;
        int x = s[l];
        while (i < j)
        {
            while (i < j && s[j] >= x)
            {
                j--;
            }
            if (i < j)
            {
                s[i++] = s[j];
            }

            while (i < j && s[i] < x)
            {
                i++;
            }
            if (i < j)
            {
                s[j--] = s[i];
            }
        }
        s[i] = x;
        quickSort(s, l, i - 1);
        quickSort(s, i + 1, r);
    }
}
#pragma once

#include <QtWidgets/QWidget>
#include <QMainWindow>
#include "ui_QThread1.h"

class QThread1 : public QWidget
{
    Q_OBJECT

public:
    QThread1(QWidget *parent = nullptr);
    ~QThread1();
signals:
    void starting(int num);

private:
    Ui::QThread1Page *ui_;
};

#include "QThread1.h"
#include "Generate.h"
#include "BubbleSort.h"
#include "QuickSort.h"
#include <QString>
#include <QDebug>
#include <QThread>

QThread1::QThread1(QWidget *parent)
    : QWidget(parent)
    , ui_(new Ui::QThread1Page)
{
    //1.初始化显示界面
    ui_->setupUi(this);

    //1.创建子线程对象
    QThread* t1 = new QThread;
    QThread* t2 = new QThread;
    QThread* t3 = new QThread;

    //2.创建对应的子线程类
    Generate* gen = new Generate;//生成随机数
    BubbleSort* bubble = new BubbleSort;//冒泡排序
    QuickSort* quick = new QuickSort;//快速排序

    //3.将任务对象移动到某个子线程中
    gen->moveToThread(t1);
    bubble->moveToThread(t2);
    quick->moveToThread(t3);

    //4.主线程的逻辑
    //connect(this, &QThread1::starting, gen, &Generate::recvNum);

    connect(ui_->btnStart, &QPushButton::clicked, this, [=]() 
    {
            t1->start();
            gen->working(10000);
    });

    //两个子线程接收数据
    connect(gen, &Generate::sendArray, bubble, & BubbleSort::working);
    connect(gen, &Generate::sendArray, quick, &QuickSort::working);

    //主线程开始显示数据,并且启动子线程的排序功能
    connect(gen, &Generate::sendArray, this, [=](QVector<int> list)->void 
    {
        for (int i = 0; i < list.size(); i++) 
        {
            ui_->randList->addItem(QString::number(list.at(i)));
        }
    });
    connect(gen, &Generate::sendArray, this, [=](QVector<int> list)->void
        {
            t2->start();
            t3->start();
        });

    //当子线程排序完数据后,在主线程中显示数据
    connect(bubble, &BubbleSort::finish, this, [=](QVector<int>list) 
    {
        for (int i = 0; i < list.size(); i++)
        {
           ui_->bubbleList->addItem(QString::number(list.at(i)));
        }
    });
    connect(quick, &QuickSort::finish, this, [=](QVector<int>list)
    {
        for (int i = 0; i < list.size(); i++)
        {
            ui_->quickList->addItem(QString::number(list.at(i)));
        }
    });

    connect(this, &QThread1::close, this, [=]()
    {
        t1->quit();
        t1->wait();
        t1->deleteLater();

        t2->quit();
        t2->wait();
        t2->deleteLater();

        t3->quit();
        t3->wait();
        t3->deleteLater();

        gen->deleteLater();
        bubble->deleteLater();
        quick->deleteLater();
        qDebug() << "process quit...";
    });

}

QThread1::~QThread1()
{}

#pragma once
#include <QPushButton>
#include <QWidget>
#include <QListWidget>
#include <QVBoxLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QWidget>
#include <QMainWindow>

//创建程序所需要的界面
class Ui_QThread1Page {
public:
    //界面所需要的组件
    QGroupBox* groupBox;
    QGroupBox* groupBox_2;
    QGroupBox* groupBox_3;
    QListWidget* randList;
    QListWidget* bubbleList;
    QListWidget* quickList;

    QHBoxLayout* hboxLayout4;
    QPushButton* btnStart;
    QVBoxLayout* vboxLayout;

    QVBoxLayout* vboxLayout1;
    QVBoxLayout* vboxLayout2;
    QVBoxLayout* vboxLayout3;

public:
    void setupUi(QWidget* parent)
    {
        groupBox = new QGroupBox;
        groupBox_2 = new QGroupBox;
        groupBox_3 = new QGroupBox;

        groupBox->setTitle("randList");
        groupBox_2->setTitle("bubbleList");
        groupBox_3->setTitle("quickList");

        randList = new QListWidget;
        bubbleList = new QListWidget;
        quickList = new QListWidget;

        hboxLayout4 = new QHBoxLayout;

        btnStart = new QPushButton;
        btnStart->setText("btnStart");
        vboxLayout = new QVBoxLayout;

        vboxLayout1 = new QVBoxLayout;
        vboxLayout2 = new QVBoxLayout;
        vboxLayout3 = new QVBoxLayout;

        vboxLayout1->addWidget(randList);
        groupBox->setLayout(vboxLayout1);

        vboxLayout2->addWidget(bubbleList);
        groupBox_2->setLayout(vboxLayout2);

        vboxLayout3->addWidget(quickList);
        groupBox_3->setLayout(vboxLayout3);

        hboxLayout4->addWidget(groupBox);
        hboxLayout4->addWidget(groupBox_2);
        hboxLayout4->addWidget(groupBox_3);

        vboxLayout->addLayout(hboxLayout4);
        vboxLayout->addWidget(btnStart);
        parent->setLayout(vboxLayout);
        parent->setFixedSize(800,600);
    }
};

namespace Ui {
    class QThread1Page :public Ui_QThread1Page {};
}

原文地址:https://blog.csdn.net/weixin_40933496/article/details/145230118

免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!