Qt QThread 探索(二)

在Qt的官方文档,大家知道有两种方式使用 QThread。

You can use worker objects by moving them to the thread using QObject::moveToThread().
Another way to make code run in a separate thread, is to subclass QThread and reimplement run().
--------------------- 

前面文章讲到了moveToThread的使用,这篇文章我们探索继承QThread的方法实现多线程。

借用官网的demo: http://doc.qt.io/qt-5/qthread.html#details

class WorkerThread : public QThread
{
    Q_OBJECT
    void run() override {
        QString result;
        /* ... here is the expensive or blocking operation ... */
        emit resultReady(result);
    }
signals:
    void resultReady(const QString &s);
};

void MyObject::startWorkInAThread()
{
    WorkerThread *workerThread = new WorkerThread(this);
    connect(workerThread, &WorkerThread::resultReady, this, &MyObject::handleResults);
    connect(workerThread, &WorkerThread::finished, workerThread, &QObject::deleteLater);
    workerThread->start();
}

虽然说这种方式也实现了多线程,但是,只有run()函数是运行在另外的线程中。假如你用信号触发WorkerThread的槽函数,你会发现这些函数都是在实例化WorkerThread的线程中运行的。

所以如果你想槽函数也是在新线程中运行(需要信号去触发槽函数),那么就需要使用moveToThread的方式了。

另外,注意多线程同时对某个对象进行操作时,考虑到线程安全问题,可能需要使用 QMutex,避免产生脏数据。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值