c++ - Qt: 如何正确使用 moveToThread(this)?

标签 c++ multithreading qt

我有这样一个类:

class myClass:public QThread

然后在它的构造函数中我做了:

myClass::myClass(){
    moveToThread(this);
    ...
}

看起来所有的成员槽实际上都在工作线程上工作。 但是在这种情况下,我怎么能在解构期间停止线程呢?

最佳答案

只是不要那样做线程。

使用 moveToThread() 的正确方法在 Qt 文档中有描述:

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 &);
};

或者通过继承QThread,比如:

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();
}

但两者不能同时出现。 关于该主题的更多信息 here

关于c++ - Qt: 如何正确使用 moveToThread(this)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30266468/

相关文章:

c++ - 为什么这个 `int` 有错误的值?

java同步和异常处理

c# - C# .WPF 中的线程调用

java - 在所有线程(池中)完成后如何打印摘要消息?

c++ - 如何在Qt中实现倒计时锁存器?

qt - 用鼠标移动物体

c++ - 如何在不可见模式下运行 qt c++ 控制台应用程序?

c++ - 在重载的全局新运算符中使用静态对象导致核心转储运行时错误

c++ - 减少 openmp 的奇怪结果

c++ - 实现一个尚未编译的接口(interface),.cpp include?