Qt之线程QThread

来源:互联网 发布:如何优化英语教学 编辑:程序博客网 时间:2024/06/10 09:44

如何使函数运行在线程中?

Qt帮助给出了两种方法。

1. 继承QThread, 重载run()函数,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();  }

2. 使用moveToThread, 需要借助一个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() {          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 &);  };


0 0
原创粉丝点击