简化QThread示例代码

2023-03-17 15:26:28 浏览数 (3)

QThread官方文档在描述线程内容时,提供了一个线程操作的方法,该方法用在大部分场景下都可以适用,但使用起来略有繁琐,需要创建一个线程执行类Worker和控制类Controller,如下代码:

代码语言:javascript复制
  class Worker : public QObject
  {
      Q_OBJECT

  public slots:
      void doWork(const QString &parameter) {
          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() {
          Worker *worker = new Worker;
          worker->moveToThread(&workerThread);
          connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
          connect(this, &Controller::operate, worker, &Worker::doWork);
          connect(worker, &Worker::resultReady, this, &Controller::handleResults);
          workerThread.start();
      }
      ~Controller() {
          workerThread.quit();
          workerThread.wait();
      }
  public slots:
      void handleResults(const QString &);
  signals:
      void operate(const QString &);
  };

小君编程时候,觉得这样做太繁琐了,将它融合到同一个类中,这样就简洁了很多。

代码语言:javascript复制
class Controller : public QObject
{
    Q_OBJECT
    QThread workerThread;
public:
    Controller() {
        this->moveToThread(&workerThread);
        connect(this, &Controller::operate, this, &Controller::doWork);
        workerThread.start();
    }
    ~Controller() {
        workerThread.quit();
        workerThread.wait();
    }

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

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

1 人点赞