从线程中分离对象

时间:2013-04-17 06:41:31

标签: c++ qt qthread qobject

简单问题:是否可以从QThread中分离QObject以将其移动到主线程?

我使用以下代码:

QThread *thread = new QThread();

MyObject *object = new MyObject();

object->moveToThread(thread);

thread->start();

在我想将MyObject实例移动到主线程之后的某个地方。

object->moveToThread(QApplication::instance()->thread());

我有以下错误:QObject::moveToThread: Current thread (0x00000001) is not the object's thread (0x00000002). Cannot move to target thread (0x00000003)

由于

1 个答案:

答案 0 :(得分:2)

由于official doc saysmoveToThread函数不能从另一个线程“拉”一个对象,它会将一个对象“推”到另一个线程。

这就是为什么如果你想改变对象的线程亲和力,你应该在当前对象的线程中进行。

我添加了一个简单的例子。

这是Worker课程:

class Worker : public QObject
{
    Q_OBJECT
public:
    explicit Worker(QObject *parent = 0);
signals:
    void done();

public slots:
    void doWork();
    void checkThread();

private:
    bool isMainThread();
};

Worker::Worker(QObject *parent) :
    QObject(parent)
{
    qDebug() << __PRETTY_FUNCTION__ 
             << QThread::currentThread() 
             << isMainThread();
}

void Worker::doWork()
{
    qDebug() << __PRETTY_FUNCTION__ 
             << QThread::currentThread() 
             << isMainThread();

    qDebug() << __PRETTY_FUNCTION__ << "Work is done";
    moveToThread(qApp->thread());
    emit done();
}

void Worker::checkThread()
{
    qDebug() << __PRETTY_FUNCTION__ 
             << QThread::currentThread() 
             << isMainThread();
}

bool Worker::isMainThread()
{
    return QThread::currentThread() == qApp->thread();
}

我们创建一个Worker对象,一个QThread对象并将它们相互连接:

QThread *thread = new QThread;
Worker *worker = new Worker;
worker->moveToThread(thread);

QObject::connect(thread, SIGNAL(started()), worker, SLOT(doWork()));
QObject::connect(worker, SIGNAL(done()), thread, SLOT(quit()));
QObject::connect(thread, SIGNAL(finished()), worker, SLOT(checkThread()));
QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));

thread->start();

这就是我们在应用程序输出中得到的结果:

Worker::Worker(QObject*) QThread(0x1034680) true 
void Worker::doWork() QThread(0x1224970) false 
void Worker::doWork() Work is done 
void Worker::checkThread() QThread(0x1034680) true 

正在主应用程序线程中创建Worker对象,然后它在新线程中完成工作。作业完成后,它会发送done()信号并将自身移回主线程。线程完成后,我们检查我们的Worker对象现在是否真的再次出现在主线程中。

但我真的不明白你为什么需要这个。