Reputation: 4625
I have Qt5/C++ code that runs in a thread. Main (thread #0) creates my new thread (thread #1), and there I created a new object ("hardware").
I would expect "hardware" object to live in thread #1, since it was created in code running in thread #1. However, after much debugging my code below shows that "hardware" lives in thread #0.
// Running in thread #1
m_hardwarePtr = new hardware();
qDebug() << "Start HW FROM Thread" << this->thread() << this->thread()->objectName();
qDebug() << "Start HW IN Thread" << m_hardwarePtr->thread() << m_hardwarePtr->thread()->objectName();
Why? I supposed I could pass the QThread to the above code and then move "hardware" into thread #1 - but I shouldn't have to...should I?
Can someone explain why this is happening and the correct way to fix this?
UPDATE:
Based on comments I want to add that my code above is in a method called FROM thread #0. When I changed my code to call the above method via a slot, it works as expected!
For the sake of others, I would like to accept an answer that explains (in the context of incorrectly calling the method directly from thread #0):
My problem is solved BTW, but I think a good explanation would help everyone.
Upvotes: 0
Views: 63
Reputation: 244301
QThread is not a Qt thread, that is, it is not a new type of thread implemented by Qt but QThread is a thread manager, so only the code executed in the run method is executed in that secondary thread, everything else will be executed in the thread to which QThread belongs as QObject.
And if the QThread was created in the main thread then everything else will be.
So you have 2 options:
override run method and there create the object of class "hardware", or
Use moveToThread.
Second is best.
Upvotes: 1