[Interest] moveToThread used in constructor to move "this"

André Somers andre at familiesomers.nl
Wed Feb 24 11:47:06 CET 2016



Op 24/02/2016 om 10:22 schreef Lorenz Haas:
> Hi André,
>
>> That should work just fine, with the exception of using &m_thread as a
>> member.
> thanks for your answer. I am, however, not sure what you mean
> regarding the m_thread member. For a better understanding here is a
> working example I have in mind:
Ah, so you want a per-object thread.
I guess your design is possible. I'm not sure it is a good idea though. 
Depending on what API you expose, you will have to assume that the 
methods called on your class are called from another thread. Or, worse, 
the caller needs to be aware of that. That gets ugly quite fast if the 
things you want to expose are not as trivial as your example below...

André

>
> **************************************************
> #include <QtCore>
>
> class Foo : public QObject
> {
>     Q_OBJECT
> public:
>     Foo() : QObject(nullptr) {
>        moveToThread(&m_thread);
>        m_thread.start();
>     }
>
>     ~Foo() {
>        m_thread.quit();
>        m_thread.wait();
>     }
>
>     void printFooInformation() const {
>        qDebug() << "foo affinity" << thread();
>     }
>
>     void printThreadInformation() const {
>        qDebug() << "m_thread affinity" << m_thread.thread();
>     }
>
> private:
>     QThread m_thread;
> };
>
> int main(int argc, char *argv[])
> {
>     QCoreApplication a(argc, argv);
>     qDebug() << "GUI affinity" << a.thread();
>     Foo *foo = new Foo;
>     foo->printThreadInformation();
>     foo->printFooInformation();
>     return a.exec();
> }
>
> #include "main.moc"
> **************************************************
>
> Of course, every instance of Foo would create a new thread and
> therefor multiple instance of Foo would _not_ share the same thread.
> Did you mean that? (In my special case this is intended.)
>
> Lorenz




More information about the Interest mailing list