Qt——另一种创建线程的方式

1.面向对象程序设计实践的早期,工程中习惯于通过继承的方式扩展系统的功能

2.解决方案------信号与槽

  • 在类中定义一个槽函数void tmain()作为线程入口函数
  • 在类中定义一个QThread成员对象m_thread
  • 改变当前对象的线程依附性到m_thread
  • 连接m_thread的start()信号到tmain()

AnotherThread.h

复制代码
#ifndef ANOTHERTHREAD_H
#define ANOTHERTHREAD_H

#include <QObject>
#include <QThread>

class AnotherThread : public QObject
{
    Q_OBJECT
    QThread m_thread;
protected slots:
    void tmain();
public:
    explicit AnotherThread(QObject *parent = nullptr);

    void start();
    void ternimate();
    void exit(int c);
    ~AnotherThread();
signals:
};

#endif // ANOTHERTHREAD_H

AnotherThread.cpp

复制代码
#include "AnotherThread.h"
#include <QDebug>

AnotherThread::AnotherThread(QObject *parent)
    : QObject{parent}
{
    moveToThread(&m_thread);

    connect(&m_thread, SIGNAL(started()), this, SLOT(tmain()));
}

void AnotherThread::tmain()
{
    qDebug() << "void AnotherThread::tmain() tid = " << QThread::currentThreadId();
    for(int i=0; i<10; i++)
    {
        qDebug() << "void AnotherThread::tmain() i = " << i;
    }
    qDebug() << "void AnotherThread::tmain() end";
}

void AnotherThread::start()
{
    m_thread.start();
}
void AnotherThread::ternimate()
{
    m_thread.terminate();
}
void AnotherThread::exit(int c)
{
    m_thread.exit(c);
}
AnotherThread::~AnotherThread()
{
    m_thread.wait();
}

main.cpp

复制代码
#include <QCoreApplication>
#include <QDebug>
#include <QThread>
#include "AnotherThread.h"

void test()
{
    AnotherThread at;
    at.start();
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    qDebug() << "main() tid = " << QThread::currentThreadId();

    test();
    return QCoreApplication::exec();
}

运行结果:

main() tid = 0x2ee4

void AnotherThread::tmain() tid = 0x38a8

void AnotherThread::tmain() i = 0

void AnotherThread::tmain() i = 1

void AnotherThread::tmain() i = 2

void AnotherThread::tmain() i = 3

void AnotherThread::tmain() i = 4

void AnotherThread::tmain() i = 5

void AnotherThread::tmain() i = 6

void AnotherThread::tmain() i = 7

void AnotherThread::tmain() i = 8

void AnotherThread::tmain() i = 9

void AnotherThread::tmain() end

相关推荐
Freak嵌入式4 小时前
树莓派 Pico GPIO 深度解析:从 MCU 架构到寄存器控制,底层原理与实践指南
java·开发语言·科技·单片机·嵌入式硬件·架构
张人玉4 小时前
基于 Python + PyQt5 的水果目标检测与分割可视化系统——水果深度学习识别可视化大屏
python·深度学习·qt·目标检测·sqlite·echarts
啊啊啊啊啊!!!!4 小时前
【c++】map和set的使用
开发语言·c++
hu9245195594 小时前
Matlab保护源代码—P文件和exe文件详细解析
开发语言·matlab
for_ever_love__4 小时前
python爬虫: GET请求与POST请求
开发语言·爬虫·python·网络编程
Freak嵌入式4 小时前
实战对比:用 mpremote/Putty/MobaXterm 连接树莓派 Pico REPL,谁更省心?
java·大数据·开发语言·科技·单片机·嵌入式硬件
ttwuai5 小时前
Go 后台管理系统组件库文档怎么写,才不会坑后续维护?
开发语言·javascript·golang
茉莉玫瑰花茶5 小时前
知识库的构建 [ 3 ]
开发语言·python
旧梦95275 小时前
Java 枚举类详解:从基础语法到高级用法
java·开发语言·python
yivifu5 小时前
查拼音程序升级版
开发语言·python