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

相关推荐
bkspiderx12 分钟前
Qt 插件机制:动态扩展应用功能的核心框架
开发语言·qt·元数据·qt 插件·qpluginloader
程序员老陆23 分钟前
深入理解 C++ thread_local:线程私有存储的正确打开方式
开发语言·c++·程序设计
沐晓时光29 分钟前
C语言入门,深入理解指针(3)
c语言·开发语言
码云数智-园园1 小时前
unique_ptr 还是 shared_ptr?C++ 智能指针选型与内存泄漏实战分析
java·开发语言
禾小西2 小时前
07丨Redis 哨兵机制:主库故障后,如何恢复服务?
java·开发语言·redis
我不是阵雨2 小时前
JDK 21虚拟线程Pinning陷阱:一文拔钉解困
java·开发语言
徐小黑ACG2 小时前
Golang 基础05 结构体struct
开发语言·算法·golang
优橙教育3 小时前
零基础学AI应用开发要多久?3个月能到什么水平
服务器·开发语言·网络·php
半杯咖啡半行码3 小时前
Qt开发实战:数据库、MV 模式、QProcess与串口通信全攻略
数据库·qt
SEO_juper3 小时前
用 Python 写一个 GEO 可见性检查脚本:你的网站现在能被 AI 引用吗
开发语言·人工智能·爬虫·python·seo·外贸独立站