PDA

View Full Version : Where a QThread lives



Althor
5th July 2010, 08:48
Hi

When I create a Qthread, where does it live? In the thread where it was created or in the new thread created when this object runs?

When we connect signals to slots of a QThread object where are this slots executed?

Thanks in advance
Regards.

tbscope
5th July 2010, 09:07
A thread has its own stack, stack pointer, program counter and processor register.
So it does not live in the main thread (the application address space).

You do have access to the application address space though through mutexes, semaphores etc...

Edit: about the signals and slots:
This is complex, it has to deal with thread affinity.
A QObject's slots and signals are bound to one single thread.
If you create a thread from within the main thread, all signals and slots go via the main thread.

To use signals and slots in the new thread, you need to call moveToThread on the object.
Example:

MyObject myNewObject;
QThread myObjectThread;
myNewObject.moveToThread(&myObjectThread);
myObjectThread.start();

Do not use moveToThread from within a subclassed thread.
Do create a new QObject with your own slots and signals and then move it from within the main thread to a new thread.

Edit again:
To clarify something:
The signals and slots of the QThread itself are ALWAYS executed in the main thread.
Only if you use moveToThread, the signals and slots of the OBJECT that is moved to a new thread (note: this is NOT the QThread object), are executed in the new thread. The QThread object will act as a path between the main thread and the object running in the new thread.

In short: QThread is NOT a new thread!!!!!!!!!!! In the example above: myObjectThread is NOT a new thread (how confusing this might be) but myNewObject does live in a new thread.