QThread的用法

QThread中含有一个run()函数,它是线程的入口点。其在QThread类中的声明如下:protected: virtual void run();所以不能直接调用run()来启动线程,而是通过调用QThread的start()方法来启动线程。当调用来start()后,run()就会被执行。QThread类中对run()的默认实现只是在函数体内调用了exec()函数而已,所以要让子线程完成特定的功能,需要通过继承QThread,然后重新实现run()来完成。或者也可以自定义一个对象,然后将
摘要由CSDN通过智能技术生成

QThread中含有一个run()函数,它是线程的入口点。其在QThread类中的声明如下:

protected:
    virtual void run();

所以不能直接调用run()来启动线程,而是通过调用QThread的start()方法来启动线程。当调用来start()后,run()就会被执行。QThread类中对run()的默认实现只是在函数体内调用了exec()函数而已,所以要让子线程完成特定的功能,需要通过继承QThread,然后重新实现run()来完成。或者也可以自定义一个对象,然后将这个对象移动到子线程中来实现。下面来分别讨论这两种做法。

1.通过QThread的子类来使用子线程

如:

#include <QThread>
#include <QDebug>

// 子线程类
class WorkerThread : public QThread
{
    Q_OBJECT
public:
    explicit WorkerThread(QObject *parent = nullptr): QThread(parent)
    {
        qDebug() <<"thread id=" << QThread::currentThreadId() << " worker thread constructor";
    }

    void run()
    {
        qDebug() <<"thread id=" << QThread::currentThreadId() << " worker thread result ready";
        emit resultReady();
        this->exec(); // 用于启动event loop,这时子线程会一直存在。除非手动调用quit()函数。如果没有这行语句,run()函数执行完返回后,就会触发子线程的finished信号。
    }

    void share()
    {
        qDebug() <<"thread id=" << QThread::currentThreadId() << " worker thread share method";
    }

public slots:
    void todo()  // 这是子线程中用于处理其他线程的信号的槽函数
    {
        qDebug() <<"thread id=" << QThread::currentThreadId() << " worker thread goon";
        QThread::sleep(10);
        qDebug() << "thread i
  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值