Qt线程关联性和moveToThread问题 [英] Issue with Qt thread affinity and moveToThread

查看:264
本文介绍了Qt线程关联性和moveToThread问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Qt中的线程将一些工作委托给一个线程,但是我无法使其正常工作.我有一个继承QMainWindow的类,该类具有一个成员对象,这些成员对象启动线程来工作.该对象具有QMainwindow作为父对象.它包含并值得注意地初始化了另一个QObject m_poller,我想将其移至我创建的线程中:

I'm trying to use threads in Qt to delegate some work to a thread, but I can't get it to work. I have a class inheriting QMainWindow that have a member object that launch threads to do work. This object has the QMainwindow as parent. It contains and initialize notably another QObject, the m_poller, which I want to move to the thread I create :

m_pollThread = new QThread;
m_poller->moveToThread(m_pollThread);
//Bunch of connection
m_pollThread->start();

我遵循了有关如何在Qt中管理线程而不对其进行子类化的准则(又名

I followed the guidelines about how to manage thread in Qt without subclassing it (aka not doing it wrong), but I still get the following message in VS :

QObject :: moveToThread:当前线程(0x2dfa40)不是对象的线程(0x120cf5c0). 无法移动到目标线程(0x1209b520)

QObject::moveToThread: Current thread (0x2dfa40) is not the object's thread (0x120cf5c0). Cannot move to target thread (0x1209b520)

我发现后续帖子似乎与相同的问题,但是无法用答案修复我的代码.我觉得我实际上是在正确地调用moveToThread(因为我没有从另一个线程中调用它来拉"一个对象),但是显然我仍然在那里缺少一些东西:如消息所暗示的那样,似乎已经有多个线程,而我对moveToThread()的调用似乎以错误的方式结束(尽管我承认我对此是全新的,并且可能会发现这完全是错误的...)

I found the following post that seems to deal with the same issue, but couldn't fix my code with the answer. I feel like I'm actually calling moveToThread correctly (as in I don't call it from within another thread to "pull" an object to it), but apparently I'm still missing something there: as the message hints, it seems there's already multiple thread and my call to moveToThread() seems to end up in the wrong one (though I admit I'm completely new to this and could figure this out completely wrong...)

那么我使用Qt线程的方式仍然可能出问题吗?

谢谢!

推荐答案

  • 您的对象没有父对象(否则父对象将具有不同的线程亲和力)
  • 您位于对象的所有者线程上,因此您实际上将对象从当前线程推"到另一个线程

因此您的错误消息表明您违反了第二种情况.您应该从创建对象的线程中调用moveToThread.
并根据您

So your error message says you're violating the second case. You should call moveToThread from the thread that created the object.
And according to you

该对象具有QMainwindow作为父对象.

This object has the QMainwindow as parent.

因此moveToThread将再次无法正常工作.您应该从m_poller对象中删除父对象

So moveToThread will not work, again. You should remove the parent from m_poller object

这篇关于Qt线程关联性和moveToThread问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆