c++multithreadingqt

QT Thread exchange data


I have a class which inherits QThread, I create several instances of this class and it makes my program multi-thread.

I'm also using slots/signals to exchange data between threads and main thread (threads creator).

I had this:

void FoundNewFile(QString SourceDrive, QString Path, QString FileName);

This was working perfect.

Now I decided to also share metadata of files, for this, I have my own large struct, so I did:

void FoundNewFile(QString SourceDrive, QString Path, QString FileName, MetaData* meta);

This MetaData is fairly large, contains different data types and have several linked structs. Now when signals emitted, in main thread, when I try to do:

meta->datetime->creationhour;

I get access denied error.

1) What I was doing (without MetaData) was right or that one was also wrong?

2) What's solution?

P.S. I tried Q_DECLARE_METATYPE and qRegisterMetaType together, didn't work.


Solution

  • Never implement new slots if you inherit QThread. It will not do what you want. A QThread object manages a thread, but it is not a thread. Your QThread-derived objects live in the main thread, so their slots will run in the main thread (not the new thread!)

    The correct solution is:

    1. Do not subclass QThread. Just instantiate a QThread object.
    2. Subclass QObject to create a worker.
    3. Instantiate your worker and move it to the new thread, using QObject::moveToThread().
    4. Start the QThread.
    5. Now, when you use signals and slots, the slots will run in the correct thread.

    See the official QThread documentation for an example.