QThread与多线程

QThread类为我们提供了一种平台无关的管理线程的方式。一个QThread对象管理应用程序中的一个线程,该线程从run()函数开始执行。并且,默认情况下,我们可以在run()函数中通过调用QThread::exec()函数来在当前线程中开启一个事件循环。

而使用QThread开启线程的最常用的方式 就是继承QThread类,重写其run()方法,因为我们刚才就说过,QThread代表的线程就是从run()函数开始运行的。

例如:

  class WorkerThread : public QThread
  {
      Q_OBJECT
      void run() Q_DECL_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()函数返回后退出。又因为我们没有在run()函数中调用exec(),所以该线程中没有运行事件循环。

另一种使用线程的方法,是将要完成的工作封装到一个工作者对象中,然后使用QObject::moveToThread()函数将该对象移动到一个线程对象中。如下:

  class Worker : public QObject
  {
      Q_OBJECT

  public slots:
      void doWork(const QString ¶meter) {
          QString result;
          /* ... here is the expensive or blocking operation ... */
          emit resultReady(result);
      }

  signals:
      void resultReady(const QString &result);
  };

  class Controller : public QObject
  {
      Q_OBJECT
      QThread workerThread;
  public:
      Controller() {
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值