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

相关推荐
2601_9669496512 分钟前
只拿到股票代码还不够:量化程序到底还需要哪些标的信息?——从数据建模开始理解股票元数据
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
m0_7345717623 分钟前
深入理解5g <十八>传输块tbsize的计算
开发语言·5g
RAN11426760082 小时前
1.3第一个程序的介绍
开发语言·qt
blue_ice .2 小时前
Verilog DDS 数字信号发生器:DAC 输出模拟波形与 ADC 回采观测
开发语言·单片机·嵌入式硬件·fpga开发
远翔调光芯片^138287988723 小时前
ECP5702能芯科技PD取电芯片在市场上的优势有哪些?
开发语言·人工智能·单片机·嵌入式硬件·智能家居
泡海椒4 小时前
规则引擎对比:JQuick-Java vs Drools 轻量场景选型对比
java·开发语言
泡泡鱼(敲代码中)4 小时前
Python 容器类型学习笔记:列表、元组、字典、集合
开发语言·笔记·python·pycharm
2501_933670794 小时前
平台招商运营校招能力模型:数据分析、SQL与增长场景拆解
开发语言
菜鸟~noob2335 小时前
【Bonjour】华为Peerium架构深度解析:从冯·诺依曼到百万处理器“一台计算机”,附MATLAB性能仿真【含matlab代码,可直接运行】
开发语言·matlab·华为·peerium
白远山5 小时前
24小时自助健身房系统开发实战:从需求分析到完整指南
java·开发语言·数据库·数据挖掘·需求分析