【QT】83.另一种创建线程的方式

思考:

通过继承的方式实现新的线程类有什么实际意义??

继承只是为了从写run,从写run就是为了指定线程的入口函数。

//QThread 类的改进
class QThread :public Qobject
{
    Q_OBJECT
    
    protected:
     virtual void run()
     {
         (void)exec();  // 开启了事件循环功能
     }   
};

问题:

如何灵活的指定一个线程对象的线程入口函数

// AnotherThread.h
class AnotherThread : public QObject
{
    Q_OBJECT

    QThread m_thread;
protected slots:
    void tmain();
public:
    explicit AnotherThread(QObject *parent = 0);
    void start();
    void terminate();
    void exit(int c);
    ~AnotherThread();
    
};

// AnotherThread.c
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";

    m_thread.quit();
}

void AnotherThread::start()
{
    m_thread.start();
}

void AnotherThread::terminate()
{
    m_thread.terminate();
}

void AnotherThread::exit(int c)
{
    m_thread.exit(c);
}

AnotherThread::~AnotherThread()
{
    m_thread.wait();
}

// mian.c
void test()
{
    AnotherThread at;

    at.start();
}

在 Qt 中通过组合的方法实现多线程类是一种常用的设计模式,其原理是直接

响应 started() 信号,在子线程中执行指定的线程体函数。

在 Qt4 之后,QThread::run() 函数中默认调用了 QThread::exec() 函数;因

此,(线程体函数)执行结束后会直接进入事件循环,导致线程永远

无法自动结束。 解决该问题的方法是,在 (线程体函数)函数的最后调用

QThread::quit() 函数,主动结束线程的事件循环。

 

 

注:参考狄泰课程做的笔记

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值